How to restrict a URL before login through middleware in Laravel?

08 Mar
2019
How to restrict a URL before login through middleware in Laravel? By Admin | Laravel, 

Laravel middleware provides an efficient way to restrict and intercept HTTP request passing though your application. For example middleware is used to identify the particular user is authenticated or not commonly and which URL’s he is able to access. If the user is authenticated then the user is able to access the URL, and if the user is not authenticated then he might be redirect to login or register page. Basically middleware is a filtering mechanism which filters HTTP request on the basis on certain condition.

There are several middleware already presents in Laravel for User Authentication, CSRF Protection and CORS Verification. We can make our own middleware in order to perform certain operation.

Defining Middleware:

For creating new middleware following Artisan command will be helpful-


> php artisan make:middleware

E.g.:

> php artisan make:middleware CheckAdmin

This artisan command will create new middleware named CheckAdmin within your directory App/Http/Middleware. We will allow only user whose user type is Admin. Otherwise we will redirect it to login page.



return $next($request);
}
return redirect(“/sign”);
}
}

 

Registering Middleware:

1) Global Middleware

If you want to run middleware foe every HTTP request to your application then list the middleware classes in $middleware property of App/Http/kernel.php class.

2) Assigning middleware to Route

If you like to assign middleware to specific route then you have to register middleware to $routeMiddleware property of App/Http/kernel.php class.

E.g.:


Protected $routeMiddleware = [


‘checkAdmin’ => ‘App/Http/Middleware/CheckAdmin::Class’,
]

Once the middleware defined inside the kernel.php then you can use it in routes like below:


Route::get(‘/dashboard’, function() {
// Some code
})->middleware(‘checkAdmin’);


Route::group([‘middleware’ => [‘web’, ‘checkAdmin’] ], function() {
// Some code
});

So with above approach you will be able to restrict user for certain URL and set permissions so that only authenticated users can access.

If you’re finding any problem with your existing Laravel application or want a new Laravel website, Hire Laravel developers from Lucid Softech and we’ll happy to help. Call us at +91-7081400666 or write to us @ contact@lucidsoftech.com for a quick start.

 

About the author : Aniket Gangathade

Aniket is Senior Laravel developer at Lucid Softech. He loves to explore Laravel. He keeps working on new ideas and currently working on some huge Laravel projects. Besides his work life, he loves watching movies and travelling.

Copyright © 2018 Lucidsoftech.com, All rights reserved.