Putting all code inside route closures quickly gets messy. A controller is a class that groups related request-handling logic.
Create a controller
Run php artisan make:controller PostController. The file is created in app/Http/Controllers.
Connect it to a route
Route::get('/posts', [PostController::class, 'index']); — this calls the index method of PostController.
Resource controllers
php artisan make:controller PostController --resource creates seven methods for CRUD. One line registers all their routes:
Route::resource('posts', PostController::class);
| Method | URL | Action |
|---|---|---|
| GET | /posts | index |
| GET | /posts/create | create |
| POST | /posts | store |
| GET | /posts/{post} | show |
| GET | /posts/{post}/edit | edit |
| PUT/PATCH | /posts/{post} | update |
| DELETE | /posts/{post} | destroy |
Keep controllers thin: receive the request, call models or services, return a response.
Example
<?php
// app/Http/Controllers/PostController.php
namespace App\Http\Controllers;
class PostController extends Controller
{
public function index()
{
$posts = ['Learn Routing', 'Learn Blade', 'Learn Eloquent'];
return view('posts.index', ['posts' => $posts]);
}
}
// routes/web.php
use App\Http\Controllers\PostController;
Route::get('/posts', [PostController::class, 'index']);
Visiting /posts runs index(), which sends the $posts array to resources/views/posts/index.blade.php.