0

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?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
fightstarr20
  • 11,682
  • 40
  • 154
  • 278

3 Answers3

3

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())
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
1

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

$user = Auth::user()->user_type;
Hedegare
  • 2,037
  • 1
  • 18
  • 22
0

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.

Jeffrey
  • 1,766
  • 2
  • 24
  • 44