All individual subscriptions are 50% off this week only!

alexandersix
1 year ago

Problem with Laravel Policies & Models

Posted 1 year ago by alexandersix

I am currently working on implementing Policies into my application, and I'm working on a policy for the User::show method.

I put a method on my User model called isAdmin() (it does what it says on the tin), and I'm trying to call it within my UserPolicy's view() method, but I'm getting a BadMethodCallException (Method Illuminate\Database\Query\Builder::isAdmin does not exist.)

Is there something I'm missing that is causing my Policy's User $user parameter to be a Builder object instead of a User Model object? I'll paste my code below for reference!

// UserPolicy.php:
class UserPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view the model.
     *
     * @param  \App\User  $user
     * @param  \App\User  $model
     * @return mixed
     */
    public function view(User $user, User $model)
    {
        $current_user = User::find($id); // I added this just in case I needed to retrieve the model from the DB

        return ($current_user->isAdmin()) || ($current_user->isInterviewer()) || $user->id === $model->id;
    }
}

// User.php
class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'first_name', 'last_name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * Checks to see if the current user is an Interviewer
     *
     * @return boolean
     */
    private function isInterviewer() : bool
    {
        return $this->role_mask & 2;
    }

    /**
     * Checks to see if the current user is an Admin
     *
     * @return boolean
     */
    private function isAdmin() : bool
    {
        return $this->role_mask & 1;
    }
}

Thanks!

Please sign in or create an account to participate in this conversation.