can() method does not work for route groups
Laravel Version
11.44.2
PHP Version
8.3
Database Driver & Version
No response
Description
Attaching Authorization middleware does not work for route groups using can() method, only via middleware('can...').
This does not work:
Route::prefix('{post}')
->can('access', 'post') // Middleware not registered.
->group(static function (): void {
Route::get('/', 'show')
...
});
Working example:
Route::prefix('{post}')
->middleware('can:access,post') // Middleware registered fine.
->group(static function (): void {
Route::get('/', 'show')
...
});
Steps To Reproduce
Route::prefix('{post}')
->can('access', 'post') // Middleware not registered.
->group(static function (): void {
Route::get('/', 'show')
...
});
Can you point where exactly this is available in Laravel documentation?
Sure: https://laravel.com/docs/11.x/authorization#via-middleware. The example shows usage on a single route without using groups, however the can() method is available on the RouteRegistrar, so IDE autocompletes it.
Thank you for reporting this issue!
As Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub.
If possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team.
Thank you!
route::livewire does not work messege error attribute livewire does not exist
Hi, can I work on this?
@rohDevellopper Feel free to open a PR to fix this! Note that there was an attempt to resolve the problem in #55135, but it was rejected. So maybe try a different approach?
I think the middleware needs to be applied correctly. I'll put it like this: Route::prefix('{post}') ->middleware('can:access,post') // Apply the middleware correctly ->group(function (): void { Route::get('/', 'show'); // Other routes... });