Laravel Route::group for Admins
11,816
You can create middleware which will check if user is an admin:
class IsAdmin
{
public function handle($request, Closure $next)
{
if (Auth::user()->permission == 'admin') {
return $next($request);
}
return redirect()->route('some.route'); // If user is not an admin.
}
}
Register it in Kernel.php
:
protected $routeMiddleware = [
....
'is.admin' => \App\Http\Middleware\IsAdmin::class,
];
And then apply it to a route group:
Route::group(['middleware' => 'is.admin'], function () {
Route::get('/user/{data}', 'UserController@getData');
Route::post('/user/{data}', 'UserController@postData');
});
Author by
Okay
Updated on June 04, 2022Comments
-
Okay almost 2 years
I would like to authentificate some routes, if the user is admin.
Route::get( '/user/{data}', 'UserController@getData' ); Route::post( '/user/{data}', 'UserController@postData' );
Now, I made it inside the Controller:
public function getData( $data = 'one' ) { if ( Auth::user()->permission == 'admin' ) { //... } else { //... } } public function postData( Request $request, $data = 'one' ) { if ( Auth::user()->permission == 'admin' ) { //... } else { //... } }
I would like to make it with Route::group, but how can I do that in the routes.php?
-
andcl about 5 yearsYes, the prebuilt authorization mechanism in Laravel lets you do that even smarterly through
Gates
... See laravel.com/docs/5.8/authorization