Search code examples
phplaravellaravel-5laravel-5.3

How to add custom middleware inside a Route group in laravel


I have a Route group in laravel which has middleware of auth

Route::group(['middleware'=>'auth', function()
{
    //Routes
});

Now these routes are only available to logged in users. I have a situation that logged in users have privileges. I have some routes that are only to be visited by logged in users AND if they have privilege of OWNER

In function I have started a session and stored privilege value.

I did something like this

Route::group(['middleware'=>'auth', function()
{
    //Routes
    if(session::get('privilege')
    {
        //Routes
    }
});

This isn't working neither it's appropriate method. Can anyone tell me how add middleware inside a middleware?


Solution

  • You will need to create a custom middleware called OWNER

    php artisan make:middleware Owner
    

    Will create a middleware file for you. Then in the public function called handle u can do something like

    if (Auth::user()->privilege == "OWNER") {
           return $next($request);
        }
    
    return redirect('home');
    

    So at the end your custom middleware will look something like this:

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    
    class Owner
    {
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
         if (Auth::user()->privilege == "OWNER") {
           return $next($request);
        }
    
        return redirect('home');
    
    }
    

    }

    More about Laravel Middelware here