0
0
Laravelframework~5 mins

Controller middleware in Laravel

Choose your learning style9 modes available
Introduction

Middleware helps control what happens before or after a request reaches your controller. It acts like a gatekeeper to add checks or actions easily.

To check if a user is logged in before allowing access to certain pages.
To log information about requests before they reach the controller.
To block users who do not have permission to access a feature.
To modify request data before the controller uses it.
To run cleanup tasks after the controller finishes processing.
Syntax
Laravel
public function __construct()
{
    $this->middleware('middlewareName');
}

// Or apply middleware to specific methods
$this->middleware('middlewareName')->only(['methodName']);
$this->middleware('middlewareName')->except(['methodName']);

Middleware is added inside the controller's constructor method.

You can apply middleware to all methods or only some methods using only or except.

Examples
This applies the 'auth' middleware to all controller methods, requiring users to be logged in.
Laravel
public function __construct()
{
    $this->middleware('auth');
}
This applies the 'auth' middleware only to the 'edit' and 'update' methods.
Laravel
public function __construct()
{
    $this->middleware('auth')->only(['edit', 'update']);
}
This applies the 'auth' middleware to all methods except 'index' and 'show'.
Laravel
public function __construct()
{
    $this->middleware('auth')->except(['index', 'show']);
}
Sample Program

This controller uses the 'auth' middleware only on the 'create' and 'store' methods. So, users must be logged in to create or save posts. The 'index' method is open to everyone.

Laravel
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth')->only(['create', 'store']);
    }

    public function index()
    {
        return 'Showing all posts';
    }

    public function create()
    {
        return 'Show form to create a post';
    }

    public function store(Request $request)
    {
        return 'Saving new post';
    }
}
OutputSuccess
Important Notes

Middleware names like 'auth' refer to middleware registered in your app's HTTP kernel.

You can create custom middleware for your own checks and use them the same way.

Middleware runs before the controller method and can stop the request or modify it.

Summary

Middleware controls access and actions before or after controller methods run.

Add middleware in the controller constructor using $this->middleware().

Use only or except to limit middleware to specific methods.