ShieldStick's avatar

Test Throwing Exception For Static Property After Implementing Policy

Hello,

What I am trying to test is very basic

class ReadPostsTest extends TestCase
{
    use DatabaseMigrations;


    public function setUp()
    {
        parent::setUp();

        $user = factory('App\User')->create();
        
        $this->signIn($user);

        $this->topic = factory('App\Topic')->create();

        $this->post = factory('App\Post')->create(['topic_id' => $this->topic->id]);

    }
    

    /** @test */
    public function an_authenticated_user_can_see_posts_associated_to_a_topic()
    {
        $this->get('/'.$this->topic->slug.'/')
            ->assertSee($this->post->title);
    }

However, after implementing a policy to my Post model its giving me this exception:

Undefined property: App\User::$is_admin

Here is my User model:

class User extends Authenticatable
{
    protected $guarded = ['id', 'is_admin'];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    public function votes()
    {
        return $this->hasMany(Vote::class);
    }

    public function is_admin()
    {
        return $this->is_admin;
    }

And here is the Post policy:

class PostPolicy
{
    use HandlesAuthorization;

     /**
     * Policies do not apply if user is admin.
     *
     * @param   $user
     * @param   $ability
     * @return mixed
     */

    public function before($user, $ability)
    {
        if($user->is_admin()) {
             return true;
        }
    }

    /**
     * Determine whether the user can edit the post.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function edit(User $user, Post $post)
    {
        return $user->id === $post->user_id;
    }

Thanks in advance!

0 likes
3 replies
tykus's avatar

Is is_admin a column in the users table; or a property property on the User model? I can't see where you are getting the is_admin property returned by your getter:

    public function is_admin()
    {
        return $this->is_admin; // this property comes from where?
    }
1 like
ShieldStick's avatar

Its a column in the users table..

protected $guarded = ['id', 'is_admin'];
ShieldStick's avatar
ShieldStick
OP
Best Answer
Level 21

Figured it out. The policy will always refer to the Auth::user() so this will work

public function before($user, $ability)
{
        return $user->is_admin;
}

My bad for adding the custom getter. Thanks @tykus !

1 like

Please or to participate in this conversation.