Controllers
While there are few routes, the code can live right in routes/web.php. But as the project grows, that file swells. A controller is a class that groups the request handlers for one part of the site, for example for posts.
Creating a controller
A controller is created with an Artisan command:
php artisan make:controller PostControllerThe file appears at app/Http/Controllers/PostController.php.
A controller method
Each method handles one request and returns a response:
namespace App\Http\Controllers;
class PostController extends Controller
{
public function index()
{
return 'List of posts';
}
}Binding to a route
The route names the class and the method:
use App\Http\Controllers\PostController;
Route::get('/posts', [PostController::class, 'index']);Route parameters
A parameter from the address arrives as a method argument:
public function show(string $id)
{
return "Post $id";
}Route::get('/posts/{id}', [PostController::class, 'show']);Request data
To read form data or the query string, add a Request object to the arguments — Laravel injects it for you:
use Illuminate\Http\Request;
public function search(Request $request)
{
$query = $request->input('q', '');
return "Searching for: $query";
}The second argument of input() is the default value when the parameter is missing.
Resource controllers
For the typical set of actions — list, view, create, update, delete — there is a ready-made template:
php artisan make:controller PostController --resourceAll seven routes are registered with one line:
Route::resource('posts', PostController::class);| Method and address | Controller method |
|---|---|
GET /posts | index |
GET /posts/create | create |
POST /posts | store |
GET /posts/{post} | show |
GET /posts/{post}/edit | edit |
PUT /posts/{post} | update |
DELETE /posts/{post} | destroy |
Common mistake
If you forget the use line for the controller in the routes file, Laravel cannot find the class and fails with Target class [PostController] does not exist. Check that use App\Http\Controllers\PostController; is at the top of routes/web.php.