← 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.
Ready to go further?

These free tutorials are a preview, our Backend Development cohort covers it in depth, with a real project and a cohort alongside you. Active

Enroll in Backend Development
Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account