How can I use Policies whithout User model?

590 views Asked by At

Today I am facing a problem. I have several levels of authentication on my site, and on my nova, I connect with the Administrators table. How can I use it to declare Policies other than with User?

I tried to do it like this:

/**
     * Determine whether the user can view any models.
     *
     * @param Administrator $admin
     * @return mixed
     */
    public function viewAny(Administrator $admin)
    {
        return $admin->superadmin == 1;
    }

The problem being that I get an error telling me that I'm not using the User model when I'm waiting for it? How can I fix this problem? I would like to give access to a nova page only to administrators who have the "superadmin" column on 1...

error

My table looks like this. It's named "administrators".

table

I've been stuck for quite a long time on this problem without really finding solutions... Do I have to use the User model?

1

There are 1 answers

0
Deepesh Thapa On

You can make use of Guest users

From laravel documentation

Guest Users By default, all gates and policies automatically return false if the incoming HTTP request was not initiated by an authenticated user. However, you may allow these authorization checks to pass through to your gates and policies by declaring an "optional" type-hint or supplying a null default value for the user argument definition:

<?php

namespace App\Policies;

use App\Models\Post;
use App\Models\User;

class PostPolicy
{
    /**
     * Determine if the given post can be updated by the user.
     *
     * @param  \App\Models\User  $user
     * @param  \App\Models\Post  $post
     * @return bool
     */
    public function update(?User $user, Post $post)
    {
        return optional($user)->id === $post->user_id;
    }
}