fightstarr20
fightstarr20

Reputation: 12598

Laravel 5.5 - Only Get Admin Users

I am getting a users details in a Laravel 5.5 controller like this...

$user = Auth::user();

But I want to do a check and see if the user has 'user_type' set to 'admin'

I know I can do a further check once I have the users info but is there a way to combine this into the one statement?

Upvotes: 0

Views: 1126

Answers (3)

Jeffrey
Jeffrey

Reputation: 1804

As you can see here, the default migration for users does not have a user_type. Hence, if you want to give users certain privileges, you'll have to create it first.

I recommand using a out-of-the-box package. You can (for example) use the package laravel permissions and roles (by Spatie) to do the work for you.

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

Create a method in User model:

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

Then use it anywhere in your code:

if (auth()->user()->isAdmin())

Or just do it manually each time:

if (auth()->check() && auth()->user()->user_type === 'admin')

You can even create a global helper and do this:

@if (isAdmin())

Upvotes: 3

Hedegare
Hedegare

Reputation: 2047

This way you can retrieve the user_type of the authenticated user:

$user = Auth::user()->user_type;

Upvotes: 1

Related Questions