Prashant Patil
Prashant Patil

Reputation: 31

Two middleware for only one Function in laravel

I can use only one middleware at a time..inside a constructor..I want to use if else condition inside constructor or two middleware.

I can use only one middleware inside constructor & if else condition also not working

I want only one function work or use according to middleware.I have two seprate table for authentication

    Following middleware pointing to diffrent table

       $this->middleware('auth:admin') - admins 
        $this->middleware('auth')- user

Example are follows

If else

class HRJob extends Controller
   {   
       public function __construct()
       {
          if(Auth::guard('admin'))
         {
          $this->middleware('auth:admin');
         }
       else
       {
       $this->middleware('auth');
        }
    }
      public function userdetails()
      {
     dd(Auth::user());
      }
    }

Two middleware

class HRJob extends Controller
 {  
   public function __construct()
       {
     $this->middleware('auth:admin');
     $this->middleware('auth');
     }

  public function userdetails()
     {
     dd(Auth::user());
      }
 }

Upvotes: 2

Views: 711

Answers (1)

Azraar Azward
Azraar Azward

Reputation: 1624

You can try like this in the controller

class UserController extends Controller
{
    /**
     * Instantiate a new UserController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');

        $this->middleware('log', ['only' => [
            'fooAction',
            'barAction',
        ]]);

        $this->middleware('subscribed', ['except' => [
            'fooAction',
            'barAction',
        ]]);
    }
}

Also you can use Middleware groups

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'api' => [
        'throttle:60,1',
        'auth:api',
    ],
];

More: https://laravel.com/docs/master/middleware

Upvotes: 3

Related Questions