maxudaskin Posted September 29, 2021 Share Posted September 29, 2021 <?php // FlightEntryController.php ... class FlightEntryController extends Controller { public function __construct() { $this->authorizeResource(FlightEntry::class); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show(FlightEntry $flight) { dd($flight); } ... } // FlightEntryPolicy.php class FlightEntryPolicy { use HandlesAuthorization; ... /** * Determine whether the user can view the model. * * @param \App\Models\User $user * @param \App\Models\FlightEntry $flightEntry * @return \Illuminate\Auth\Access\Response|bool */ public function view(User $user, FlightEntry $flightEntry) { dd($user); if($user->hasPermissionTo('view flights not owned')) { // Spatie return Response::allow(); } if($user->id === $flightEntry->user_id) { return Response::allow(); } return Response::deny(null, 404); } ... } // AuthServiceProvider.php class AuthServiceProvider extends ServiceProvider { /** * The policy mappings for the application. * * @var array */ protected $policies = [ App\Models\FlightEntry::class => App\Policies\FlightEntryPolicy::class, ]; ... } // routes/web.php Route::resource('/flights', FlightEntryController::class)->middleware('auth'); With the policy not attached, everything works fine. When I attach the policy, index (viewAny) works, but show (view) does not. It throws a 403 and does not run the dd inside. I'm going crazy. Any suggestions? Quote Link to comment https://forums.phpfreaks.com/topic/313837-laravel-policy-always-returning-403-on-view/ Share on other sites More sharing options...
gizmola Posted October 2, 2021 Share Posted October 2, 2021 Route::resource is rarely what you want in the long run, as it magically routes to a lot of methods your controller may not have. With that said, start with the output of php artisan route:list What is it showing you? There are alternatives to what you are trying to do like moving the middleware to your FlightEntryController constructor. $this->middleware('auth'); // Or to except certain routes $this->middleware('auth')->except(['index']); Other standard configuration route based options differ depending on your version of Laravel, but typically involve using a route group to wrap the resource. Something like: //change routes/web.php to this Route::group(['middleware' => 'auth'], function() { Route::resource('flights', 'FlightEntryController'); }); Quote Link to comment https://forums.phpfreaks.com/topic/313837-laravel-policy-always-returning-403-on-view/#findComment-1590612 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.