Search code examples
phplaravelauthenticationurllaravel-middleware

How to disable middleware only for specific function in controller if user pass data from a specific route in Laravel


Requirement

If data were passed into the function via a specific route then middleware authentication to be escaped only for a specific functions.

What I have tried

So I know I can use below method to escape middleware authentication for a specific function I want But when I do this it will ignore authentication for spec_add function from all routes.

  public function __construct ()
    {
        $this -> middleware ( 'auth'  ,['except' => ['spec_add']]) ;
    }

I know I can implement something like below. But what I wants to know that is there is a better way to do this rather than below method.

public function __construct ()
{
    if (  url () -> previous () == 'special_url'){
        $this -> middleware ( MiddlewareConstants::Auth . ':' . GuardConstants::Customers  ,['except' => ['addAddress']]) ;
    }else{
        $this -> middleware ( MiddlewareConstants::Auth . ':' . GuardConstants::Customers  ) ;

    }
}

Thanks


Solution

  • In your web.php give this a shot

    Route::group(['middleware' => 'auth',], function () {
       // all the routes here will have to go through auth
    });
    
    // this will not
    Route::get('spec_add', 'TestController@function');
    

    Hope it helps. Cheers!