Laravel middleware for admin or auth in laravel 5

Make Sure your have role column or attribute in database users table.

STEP 1

Create a Midlleware

php artisan make:middleware AnyNameYouWant

it will create a nice boilerplate for you.

STEP 2

 public function handle($request, Closure $next)
{
    if (\Auth::user()->role == 'admin') {
      return $next($request);
    }

      return redirect('home');
}

STEP 3

Use this in Kernel

protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin' => \App\Http\Middleware\YourMiddleware::class,

];

STEP 4

Protect your routes.

Route::get('admin/profile', function () {
//
})->middleware('admin');

You are done


The best way to learn is straight from the Laravel docs: https://laravel.com/docs/5.4/middleware

or you can just watch a short Laracasts video: https://laracasts.com/series/laravel-5-from-scratch/episodes/14

Tags:

Php

Laravel