What should I use in controller’s constructor for authenticating my methods in laravel 11.
<?php
public function __construct(){
$this->middleware('auth:sanctum')->except(['index', 'show']);
}
?>
We used write this before laravel 11.
Now what should we need to use instead of this?
I haven’t tried anything
2
Answers
This has changed significantly in Laravel 11.
https://laravel.com/docs/11.x/controllers#controller-middleware
It is recommended to specify middleware using routing.
In Laravel 11, the abstract controller class no longer extends any class or uses any traits, so the old
middleware()
method is no longer available.If you want to use the same functionality, your controller needs to implement the
IlluminateRoutingControllersHasMiddleware
interface which contains a singlemiddleware()
method.This
middleware()
method returns an array of middleware to be applied inside the controller. If you want to have finer control over the methods to which the middleware will be applied or excluded then you can include an instance of the classIlluminateRoutingControllersMiddleware
inside this array. Here’s how we can rewrite your example using Laravel 11 approach:Further information are available in the official documentation here: https://laravel.com/docs/11.x/controllers#controller-middleware