← Laravel tutorial

Laravel

Controllers

A controller groups related route logic into one class instead of scattering closures across routes/web.php.

Example: a controller and the route pointing at it

// app/Http/Controllers/PostController.php
class PostController extends Controller
{
    public function index()
    {
        return view('posts.index', ['posts' => Post::all()]);
    }
}

// routes/web.php
Route::get('/posts', [PostController::class, 'index']);

Visiting /posts now runs the controller's index method, which renders the posts.index Blade view with every Post passed in as $posts. Generate one with php artisan make:controller PostController rather than creating the file by hand — artisan scaffolds the correct class structure automatically.

Example
// app/Http/Controllers/PostController.php
class PostController extends Controller
{
    public function index()
    {
        return view('posts.index', ['posts' => Post::all()]);
    }
}

// routes/web.php
Route::get('/posts', [PostController::class, 'index']);
Output
Visiting /posts renders the posts.index Blade view with every Post passed in as $posts.