Mastering Laravel Controller – Part 1

aravel Laravel Views & Blade Templates – Beginner’s Guide

Laravel Controllers Tutorial

In Laravel, instead of writing all your logic directly inside routes, you can organize it using controllers.
Controllers help you group related request-handling logic into one class. For example, a UserController might handle everything related to users — showing profiles, creating new users, updating data, or deleting users.

By default, controllers live inside the app/Http/Controllers directory.


Creating a Basic Controller

Laravel provides an Artisan command to create controllers:

php artisan make:controller UserController

This will create a file:

app/Http/Controllers/UserController.php

Example of a Basic Controller

Let’s say we want to show a user profile.
Here’s how our controller might look:

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\View\View;

class UserController extends Controller
{
    /**
     * Show the profile for a given user.
     */
    public function show(string $id): View
    {
        return view('user.profile', [
            'user' => User::findOrFail($id)
        ]);
    }
}

Here:

  • The show() method takes a user ID.
  • It fetches the user from the database.
  • It passes the user data to a view (resources/views/user/profile.blade.php).

Defining Routes for Controllers

To connect the controller method to a URL, define a route:

use App\Http\Controllers\UserController;

Route::get('/user/{id}', [UserController::class, 'show']);

Now, if you visit:
http://your-app.test/user/1 → it will call the show() method and display that user’s profile.


Single-Action Controllers

Sometimes, you only need one action in a controller (instead of multiple methods).
For that, Laravel provides invokable controllers.

Example:

<?php

namespace App\Http\Controllers;

class ProvisionServer extends Controller
{
    /**
     * Provision a new web server.
     */
    public function __invoke()
    {
        // Your logic here...
    }
}

Route for Invokable Controller

use App\Http\Controllers\ProvisionServer;

Route::post('/server', ProvisionServer::class);

Create an Invokable Controller

php artisan make:controller ProvisionServer --invokable

Applying Middleware to Controllers

Middleware is used to filter or secure requests (e.g., authentication).

Option 1: Add middleware in routes

Route::get('/profile', [UserController::class, 'show'])
    ->middleware('auth');

Option 2: Add middleware inside the controller

You can define middleware directly in your controller using the HasMiddleware interface:

<?php

namespace App\Http\Controllers;

use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;

class UserController extends Controller implements HasMiddleware
{
    /**
     * Get the middleware that should be assigned to the controller.
     */
    public static function middleware(): array
    {
        return [
            'auth',
            new Middleware('log', only: ['index']),
            new Middleware('subscribed', except: ['store']),
        ];
    }
}

Explanation:

  • auth → applies to all methods.
  • log → applies only to index().
  • subscribed → applies to all except store().

Using Inline Middleware (Closures)

You can even define middleware as closures inside the controller:

use Closure;
use Illuminate\Http\Request;

public static function middleware(): array
{
    return [
        function (Request $request, Closure $next) {
            // Custom logic here
            return $next($request);
        },
    ];
}

Important

  • Controllers organize logic into classes instead of keeping everything in routes.
  • Use php artisan make:controller to generate one.
  • Routes can point to controller methods ([Controller::class, 'method']).
  • For single-purpose controllers, use invokable controllers.
  • Apply middleware via routes or inside controllers.
  • Middleware can be class-based or closure-based.