Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel middleware for admin or auth in laravel 5

Tags:

php

laravel

i am new to laravel and don't know about laravel restriction mechanism, i have read about middleware but confused how to use it and why it is used and how this will works, so please guide me how i can implement it for restriction purposes i.e for auth, sa user routes.

like image 405
Muhammad Amir Avatar asked Feb 26 '17 19:02

Muhammad Amir


People also ask

What is middleware Auth Laravel?

Using the Auth Middleware Middlewares provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen.

How do I use Auth API middleware in Laravel?

Please run php artisan make:middleware UserAccessible on your terminal. After run above artisan command, you will see generated a file named UserAccessible. php in the App/Http/Middleware folder. Route::group(['middleware' => ['auth:api', 'user_accessible']], function () { // your protected routes. });

How do I authenticate a user and admin in Laravel?

Just run php artisan make:auth and php artisan migrate in a fresh Laravel application. Then, navigate your browser to http://your-app.test/register or any other URL that is assigned to your application. These two commands will take care of scaffolding your entire authentication system!


Video Answer


2 Answers

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

like image 78
Romantic Dev Avatar answered Oct 10 '22 20:10

Romantic Dev


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

like image 23
Paras Avatar answered Oct 10 '22 21:10

Paras