In this example i added middleware for check if user is admin then it can open someroute like ACL. So i added id_admin column in my users table if use have is_admin = 1 then it can access "admins" route. So first create IsAdminMiddleware middleware using bellow command:
Create Middleware
php artisan make:middleware IsAdminMiddlewareOk, now you can found IsAdminMiddleware.php in app/Http/Middleware directory and open IsAdminMiddleware.php file and put bellow code on that file. In this file i check first if user is not login then it will redirect home route and other if user have not is_admin = 1 then it will redirect home route too.
app/Http/Middleware/IsAdminMiddleware.php
namespace App\Http\Middleware;
use Closure;
use Auth;
class IsAdminMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(!Auth::check() || Auth::user()->is_admin != '1'){
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 App\Http;Now we are ready to use is-admin middleware in routes.php file. so you can see how to use middleware in routes.php file.
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
......
protected $routeMiddleware = [
......
'is-admin' => \App\Http\Middleware\IsAdminMiddleware::class,
];
}
app/Http/routes.php
Route::get('home', ['as'=>'home','uses'=>'HomeController@index']);OR
Route::group(['middleware' => 'is-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' => 'is-admin']);
No comments:
Post a Comment