How to Create Middleware with Parameters in Laravel?
In this post we will give you information about How to Create Middleware with Parameters in Laravel?. Hear we will give you detail about How to Create Middleware with Parameters in Laravel?And how to use it also give you demo for it if it is necessary.
Laravel is the best framework in PHP todays. Laravel framework provide saveral functionality and you can also find from this site. But now in this post you can learn how to create custom middleware with passing parameters in laravel 5 example and how to use middleware with route parameters in laravel 5. In this example you can learn how to add middlware with check user have access role for this route from scratch in your laravel application.
I also added how to create middleware in my previous post, you can see that also.
In this example i added middleware for check use have role access for this route. So i added
Create Middleware
php artisan make:middleware RoleMiddleware
Ok, now you can found RoleMiddleware.php in app/Http/Middleware directory and open RoleMiddleware.php file and put bellow code on that file. In this file i check given parameter role is access for current login user or not.
app/Http/Middleware/RoleMiddleware.php
namespace AppHttpMiddleware;
use Closure;
use Auth;
class RoleMiddleware
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $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 we need to register and create aliase above middleware in Kernel.php file so first open Kernel.php and add bellow line.
app/Http/Kernel.php
namespace AppHttp;
use IlluminateFoundationHttpKernel as HttpKernel;
class Kernel extends HttpKernel
{
......
protected $routeMiddleware = [
......
'role' => AppHttpMiddlewareRoleMiddleware::class,
];
}
Now we are ready to use role middleware in routes.php file. so you can see how to use middleware in routes.php file.
app/Http/routes.php
Route::get('home', ['as'=>'home','uses'=>'HomeController@index']);
Route::group(['middleware' => 'role:admin'], function () {
Route::get('admins', ['as'=>'admins','uses'=>'HomeController@admins']);
});
OR
Route::get('home', ['as'=>'home','uses'=>'HomeController@index']);
Route::get('admins', ['as'=>'admins','uses'=>'HomeController@admins','middleware' => 'role:admin']);
you can pass also multiple parameters as you want….
Hope this code and post will helped you for implement How to Create Middleware with Parameters in Laravel?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs