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.
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.
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. });
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With