aceraven777
aceraven777

Reputation: 4556

How to require middleware with a middleware?

I've create a middleware lets say AuthenticateAdmin, and in Kernel.php I've added the code:

'auth_admin' => \App\Http\Middleware\AuthenticateAdmin::class,

In my routes I have this code:

Route::group(['middleware' => 'auth_admin'], function () {
    // Admin routes here
});

In my AuthenticateAdmin.php I have this code"

<?php namespace App\Http\Middleware;

use Auth;
use Closure;
use Illuminate\Contracts\Auth\Guard;

class AuthenticateAdmin {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Perform action here

        return $next($request);
    }

}

What I want to do is everytime I use the middleware 'auth_admin', before going in the 'auth_admin' middleware, I want it to perform the 'auth' middleware first.

Upvotes: 2

Views: 2738

Answers (2)

Dimitri Acosta
Dimitri Acosta

Reputation: 1816

You could try using dependency injection, in the constructor you should place the auth middleware and then perform the actions for the auth_admin

<?php

namespace App\Http\Middleware;

use Auth;
use Closure;
use Illuminate\Contracts\Auth\Guard;

class AuthenticateAdmin {
    /**
     * Create a new authentication controller instance.
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Perform action here

        return $next($request);
    }

}

One more thing, remember to follow the PSR-2 standard placing the namespace in the next line just like I did in the example.

Upvotes: 2

Chung
Chung

Reputation: 975

I'm not sure why you need to do that. But in Laravel, I think you can config like following to make it work :

Route::group(['middleware' => ['auth','auth_admin']], function () {
    // Admin routes here
});

Upvotes: 0

Related Questions