In this article we will go through the basics of creating a basic route to kickstart our application.
After briefly gazing over all the different folders of a Laravel app , you may find a little ... but significant... folder named "Controllers". Specifically, the folder should be in: app/Http/Controllers
Now, there is a way to generate a controller template, through artisan of course, to get us started:
php artisan make:controller UserController
After entering the command, the terminal will then ask what kind of controller we would like: resource, api, singleton, etc. Now depending on what kind of app it is we would normally choose between resource for templates like blade, or API for front end consumption.
Basically all those options generate variations of the following functions inside a controller: index, create, store, show, edit, update, destroy.
Next step would be for us to define all those functions in the controller as they are supposed to represent HTTP verbs like : GET, PUT, DELETE.
For example:
<?php
namespace App\Http\Controllers;
use App\Models\User;
class UserController extends Controller
{
public function show(User $user)
{
return view('users.show', compact('user'));
}
}
Laravel already ships with a User model but If we were to have a different kind of controller we would need to generate the respective model as well.
Last part would be to configure our route in the web.php file located in the
routes/ folder like so:
Route::resource('users', UserController::class);
What we just achieved was to create a very minimal and basic controller. Next steps would be to create a view for it and that's it! We got our first controller in Laravel.