Reputation: 2191
I have two types of user roles. Admin and manager. An admin can to to all the routes, but a manager can only access some of them. Most of my routes are resource route. Currently I have this route group for admin:
Route::middleware(['auth', 'admin'])->prefix('admin')->group(function () {
Route::resource('post','PostController')
}
Here is my 'admin' middleware if you need to check:
if (!Auth::user()->isAdmin())
{
return redirect('/home');
}
return $next($request);
Here, all the routes are accessible by the admin. But I want to allow access some of the routes such as post.index, post.show, post.edit
for the manager.
What should I do now?
Below I am explaining my question elaborately with and example
I have three middleware, auth, manager, admin
. As the name suggests, auth
middleware checks if a user is authenticated, manager
middleware checks if the user is manager and certainly admin
middleware checks if the user is admin.
Now, for Route::resource('post','PostController')
route,
auth
has access to post.index, post.view
manager
has access to post.index, post.view, post.edit
admin
has access to all the routes.
What is the best way to apply middleware to solve the problem?Upvotes: 0
Views: 3609
Reputation: 2709
You can define partial ressource routes.
https://laravel.com/docs/7.x/controllers#restful-partial-resource-routes
So you can define some of them in your middleware group and the other ones outside of it.
Route::middleware(['auth'])->group(function(){
Route::middleware(['admin'])->prefix('admin')->group(function () {
Route::resource('post','PostController')->except([
'index', 'show', 'edit'
]);
}
Route::middleware(['manager'])->prefix('manager')->group(function () {
Route::resource('post','PostController')->only([
'index', 'show', 'edit'
]);
}
}
Upvotes: 0
Reputation: 359
Laravel allows for multiple routes in your controllers
Follow the following steps:
Remove the 'admin' middleware from your route group, leaving just 'auth'.
Route::middleware(['auth'])->prefix('admin')->group(function()
{
Route::resource('post','PostController');
}
In your 'manager.php' route file now, you can use and point to the same PostController
Route::middleware(['auth'])->prefix('manager')->group(function()
{
Route::resource('post','PostController');
}
then add a __construct() method at the top of the PostController like this
class PostController extends Controller
{
public function __construct()
{
$this->middleware('admin')->except(['index', 'show', 'edit']);
$this->middleware('manager');
}
}
Upvotes: 4