Laravel Gate using User data instead of specified parameter

Viewed 15

I'm trying to understand Gates, Permissions and Authentication better so I've created two Gates in my AuthServiceProvider. "isPermitted" checks if the user is permitted to access the given role and "isProjectRole" checks if the project given falls under the role the user is permitted to use.

My issue is that for some reason, the data passed to the isProjectRole Gate is incorrect, as it seems to be passing the User Facade instead of the project ID, which obviously comes back with the error that the User Facade can't be compared to an integer. But when I use DD to get the User, project ID and role ID it comes out as normal.

Using the DD inside of the controller

enter image description here

Using the DD inside the isProjectRole Gate

enter image description here

The routes are as follows:

Route::group(['middleware' => ['auth']], function () {
  Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('welcome');
  Route::get('/map/{role}/{project}', [App\Http\Controllers\MapController::class, 'index']);
});

Here's the code from my controller.

public function index(Request $request, $role, $project)
  {
      $user = Auth::user() ?? 'null';
      // return dd('user: ' . $user->name . ' role: ' . $role . ' project: ' . $project);

      
      if(Gate::denies('isProjectRole', $role, $project)){ // Project validation
        return dd('You are not permitted to view this project.');
      }

      if(Gate::allows('isPermitted', $user->id, $role)){
....

Here's the code from the AuthServiceProvider.

    public function boot()
    {
        $this->registerPolicies();

        Gate::define('isPermitted', function($user, $role){
          $userRole = DB::table('users')
            ->join('user_roles', 'users.id', '=', 'user_roles.user_id')
            ->join('roles', 'roles.id', '=', 'user_roles.role_id')
            ->select('roles.id')
            ->where('users.id', '=', $user->id)
            ->where('roles.id', '=', $role)
            ->first();
          return $userRole ? true : false;
          //return [$user, $role];
        });

        Gate::define('isProjectRole', function($roleId, $projectId){
          // return dd($projectId, $roleId);
          $projectIsInRole = DB::table('roles')
            ->join('role_projects', 'roles.id', '=', 'role_projects.role_id')
            ->join('projects', 'projects.id', '=', 'role_projects.project_id')
            ->select('projects.id')
            ->where('roles.id', '=', $roleId)
            ->where('projects.id', '=', $projectId)
            ->first();
          return $projectIsInRole ? true : false;
        });
    }

Any help would be greatly appreciated. If I've left anything out that might help, please let me know.

0 Answers
Related