I'm building a website in Laravel. I'm trying to allow the view/modification of a Model only to the user that created it. I registered the policy and use a middleware in the route to restrict the view/modification/delete/update operations but I'm always unauthorized.
TrashPrivateReportPolicy:
class TrashPrivateReportPolicy
{
use HandlesAuthorization;
public function before(User $user){
if($user->can('manage_all_projects')){
return true;
}
}
public function results(User $user, TrashPrivateReport $trash_private_report){
return $user->reports()->map(function($report){$report->trash_report();})->contains($trash_private_report);
}
}
AuthServiceProvider
class AuthServiceProvider extends ServiceProvider
{
protected $policies = [
//'App\Model' => 'App\Policies\ModelPolicy',
'App\TrashPrivateReport' => 'App\Policies\TrashPrivateReportPolicy',
];
public function boot()
{
$this->registerPolicies();
Gate::before(function($user,$ability){
return $user->abilities()->pluck('name')->contains($ability);
});
}
}
routes: web.php
Route::get('/trash_private_reports/results/{trash_private_report}','TrashPrivateReportController@results')->name('trash_private_reports.results')->middleware('can:results,trash_private_report');
So when I'm connected as a lambda user and want to see the page results
'/trash_private_reports/results/id/' access is forbidden.
The policy does not seems to be called. I tried dd(..) in the method of the policy and nothing happens.
Changing the policies array to:
TrashPrivateReport::class => TrashPrivateReportPolicy::class
Updating and clearing:
composer dump-autoload
php artisan route:clear
php artisan view:clear
php artisan config:clear
Thank you for the help :)
Edit:
I solved the problem by replacing before by after
Gate::after(function($user,$ability){
return $user->abilities()->pluck('name')->contains($ability);
});