Hello to all, welcome to therichpost.com. In this post, I will tell you, How to create custom middleware in laravel for user authorize? I am doing with laravel first time in my website. Laravel is one of the top php mvc framework.
Here are the steps in laravel for making middleware:
I have done this code in laravel 5.3.
1. First you need to create CheckRoleSuperAdmin.php file into your app/Http/Middleware/ folder and you need to below code into that file and I have used Sentinel for user permission system:
<?php
namespace App\Http\Middleware;
use Closure;
use Sentinel;
use Session;
class CheckRoleSuperAdmin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{if(Sentinel::check())
{
$user_role = Sentinel::inRole(‘super-admin’);
if($user_role) {
if(Session::get(‘activeRole’) == ‘super-admin’) {
return $next($request);
}
}
}}
}
?>
2. After this add below code into your app/Http/Kernel.php file:
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
…./**
* The application’s route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
….
‘superAdmin’=>\App\Http\Middleware\CheckRoleSuperAdmin::class,
];
}
3. For check Middleware support you can assign CheckRoleSuperAdmin middleware to particular Route and Controller and below is the example code and you can this code into your routes/web.php file:
Route::post(‘/delete’, ‘UserController@deleteUser’)->middleware(‘superAdmin’);
There are so many code tricks in laravel and i will let you know all. Please do comment if you any query related to this post. Thank you. Therichpost.com
Recent Comments