Home Laravel How to Create Middleware with Parameters in Laravel?

How to Create Middleware with Parameters in Laravel?

by Shahriar Sagor
Create Middleware with Parameters in Laravel

We are know that laravel is the best framework in PHP. Laravel framework provide us the several functionality and you can also find from this site also. But now here in this post you can learn about how to create a custom middleware with passing parameters in laravel application example and also know how to use middleware with route parameters in your laravel application . Now in this example we will about learn how to add middlware with check the user have access role for this route from the scratch in our laravel application. here we know How to Create Middleware with Parameters in Laravel?

So here I will also add how to create a middleware in my previous post, you can see that also.

Now in this example i will add middleware for the check user have role access or not for this route.

So at first need to create RoleMiddleware middleware by using bellow command:

Create Middleware
php artisan make:middleware RoleMiddleware

Okay , now we can found the RoleMiddleware.php in location  app/Http/Middleware directory and need to open RoleMiddleware.php file and then put the bellow code on that file. So in this file i will check given parameter role is access for the current login user or not.


namespace App\Http\Middleware;
use Closure;
use Auth;
class RoleMiddleware
     * Handle an incoming request.
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
    public function handle($request, Closure $next, $role)
    	if (! $request->user()->hasRole($role)) {
            return redirect()->route('home');
        return $next($request);

Now you have to register and create the aliase above the middleware in Kernel.php file. So at first open Kernel.php and add the bellow line.


namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
	protected $routeMiddleware = [
        'role' => \App\Http\Middleware\RoleMiddleware::class,

Hope now we are ready to use role middleware in our routes.php file. So we can see here how to use middleware in routes.php file.


Route::get('home', ['as'=>'home','uses'=>'HomeController@index']);
Route::group(['middleware' => 'role:admin'], function () {     
    Route::get('admins', ['as'=>'admins','uses'=>'HomeController@admins']); 


Route::get('home', ['as'=>'home','uses'=>'HomeController@index']);
Route::get('admins', ['as'=>'admins','uses'=>'HomeController@admins','middleware' => 'role:admin']);

Read Also : Laravel 8 Mobile Number Verification Tutorial

Thanks for read. I hope it help you. For more you can follow us on facebook


You may also like