简体   繁体   中英

Laravel Gate Issue

I'm trying to check if a user is allowed to view a page using Gates and Policies in Laravel. In my web.php , I have within a route:

$litter = Litter::find($id);

//Security gate
if(Gate::allows('edit-litter', Auth::user(), $litter)){
  return View::make('mykennel.litters.pupsheet')->with([
    //some variables
  ]);
}else{
  $ip_info = log_user_connection('Authorization Error');
  return View::make('errors.authorization')->with([
    'ip_info' => $ip_info,
    'litter_id' => $litter->id,
    'user_id' => Auth::user()->id,
    'litter_user' => $litter->user_id
  ]);
}

My policy is like such ( AuthServiceProvider.php ):

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

      Gate::define('edit-litter', function ($user, $litter) {
          return $user->id == $litter->user_id;
      });
  }

When I test this, I'm only ever getting the auth error, so I decided to check if I'm not seeing something by sending those variables above to the error view, and sure enough, the user_id equals litter_user (the two things I'm comparing):

{$litter_user}}, {{$user_id}} //returns '55, 55'

Am I missing something obvious? Any help appreciated.

Looks like you are checking ability in wrong way

allows() function requires two params first is ability and second is array of arguments

public function allows($ability, $arguments = [])
{
    return $this->check($ability, $arguments);
}

But you are calling it as:

Gate::allows('edit-litter', Auth::user(), $litter)

That can be the reason of your code not working

So change it to:

Gate::allows('edit-litter', $litter) 

and try again because laravel will automatically check it for authenticated user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM