CunnertA
CunnertA

Reputation: 185

Laravel 5.8, Auth::user() is not using User model

I have a function in my User model which is called isAdmin, if "Admin" is set to 1 in the database, it returns true, if not it returns false.

How is this gonna work with Auth::user()?

When I do Auth::user()->isAdmin(), it returns "Property [admin] does not exist on this collection instance."

Thats why I came to the conclusion it may not use the User model?

User model

public function isAdmin() {
   if($this->admin == 1) {
        return true;
     } else {
        return false;
   }
}
public function view () 
    {
        if(Auth::check() && Auth::user()->isAdmin()) {
            $user  = User::all();
            $post  = Post::all();
            $visit = Visits::all();


            return view('admin')->with('post', $post)->with('user', $user)->with('visit', $visit);
        } else {
            return redirect()->to('/');
        }
    }

Upvotes: 1

Views: 2481

Answers (3)

user3532758
user3532758

Reputation: 2271

If I may suggest, for this use case, you can actually make do without an extra function. You could just say auth()->user()->admin, specially if the 'admin' column in the database is boolean type.

Otherwise (even admin column is not boolean type) you can set up a mutator method in the model, like so:

public function getIsAdminAttribute()
{
   return (bool) $this->admin;
}

Then to check you can access it like so: Auth::user()->isAdmin or auth()->user()->isAdmin

And better yet, you might want to read about Gate and Policies to achieve more robust access controlling. https://laravel.com/docs/5.7/authorization

Upvotes: 1

albus_severus
albus_severus

Reputation: 3712

No Need To do anything just check if login then auth()->check() is return true then auth()->user() return the user

public function view () 
    {
        if(auth()->check() && auth()->user()->isAdmin()) {
            $user  = User::all();
            $post  = Post::all();
            $visit = Visits::all();


            return view('admin')->with('post', $post)->with('user', $user)->with('visit', $visit);
        } else {
            return redirect()->to('/');
        }
    }
public function isAdmin()
    {
        return $this->admin;

    }

Upvotes: 0

nakov
nakov

Reputation: 14298

Suggestion, change the code to just this:

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

This code does exactly the same as you've got above..

Now in your admin.blade.php you are using:

$user->isAdmin();

But in the controller you have:

$user  = User::all();

which returns collection.

You should iterate over it, and check on each user instance if it is an admin:

$users  = User::all();

In the view:

@foreach($users as $user)
 @if($user->isAdmin())
    {{ $user->name }} // some code here..
 @endif
@endforeach

Upvotes: 0

Related Questions