Middleware helps control what happens before or after a request reaches your controller. It acts like a gatekeeper to add checks or actions easily.
Controller middleware in 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.
public function __construct()
{
$this->middleware('auth');
}public function __construct()
{
$this->middleware('auth')->only(['edit', 'update']);
}public function __construct()
{
$this->middleware('auth')->except(['index', 'show']);
}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.
<?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'; } }
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.
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.