best way to call Laravel Auth helper method

Viewed 2118

i have a simple user table

-id
-name
-email
-role

should i use the first or the second method ?!

the first method

1.

if(auth()->user()->role == 'admin')
{
   // do something
}
else if (auth()->user()->role == 'supervised')
{
  // do something
}
else{
  //this is a simple user
}

and this is the second method

2.

$auth = auth()->user();
if($user->role == 'admin')
{
   // do something
}
else if ($user->role == 'supervised')
{
  // do something
}
else{
  //this is a simple user
}

does this method auth()->user() call the database each time i call it !!!?

2 Answers

It doesn't make multiple calls when you use auth()->user() or relationships (it is loaded/set). You may install clockwork and check it.

Still, I wouldn't make these comparisons outside of the User class. Add these methods to your user model.

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

public function isSupervised()
{
    return $this->role === 'supervised';
}

and use them like;

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

I would use the first method instead of creating an unneccesary variable. It won't make multiple calls to the database. Check out the user() method in SessionGaurd.php

// If we've already retrieved the user for the current request we can just
// return it back immediately. We do not want to fetch the user data on
// every call to this method because that would be tremendously slow.
if (! is_null($this->user)) {
    return $this->user;
}
Related