skip to Main Content

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


  1. This has changed significantly in Laravel 11.
    https://laravel.com/docs/11.x/controllers#controller-middleware

    <?php
     
    namespace AppHttpControllers;
     
    use AppHttpControllersController;
    use IlluminateRoutingControllersHasMiddleware;
    use IlluminateRoutingControllersMiddleware;
     
    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']),
            ];
        }
     
        // ...
    }
    

    It is recommended to specify middleware using routing.

    Login or Signup to reply.
  2. 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 single middleware() 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 class IlluminateRoutingControllersMiddleware inside this array. Here’s how we can rewrite your example using Laravel 11 approach:

    <?php
    
    namespace AppHttpControllers;
    
    use IlluminateHttpRequest;
    use IlluminateRoutingControllersMiddleware;
    
    class HomeController extends Controller implements IlluminateRoutingControllersHasMiddleware
    {
        //
        public static function middleware(): array
        {
            return [
                new Middleware(middleware: 'auth:sanctum', except: ['index', 'show']),
            ];
        }
    }
    

    Further information are available in the official documentation here: https://laravel.com/docs/11.x/controllers#controller-middleware

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search