Lovelock
Lovelock

Reputation: 8085

Should I use laravel Auth::user everytime I reference or define once on page

using Laravel 4 and its Auth feature.

Let say I want to check if the logged in ID matches that of the blog creator ID.

if (Auth::user()->id == $blog->blogOwnerID) 
{
  // do something
}

That works fine, but I need to check this in various places in the page.

The other option would be to set the user ID and blog creator ID as variables for easier use.

// at start of page
$blogOwnerID = $blog->blogOwnerID;
if (Auth::check())
{
  $userID = Auth::user()->id;
}

Now im not sure if there would be any performance gains from not calling the functions everytime, unless when referencing the variable it does the check anyway.

Just looking for the correct way of doing things :)

Craig.

Upvotes: 1

Views: 336

Answers (1)

Jonathan Crowe
Jonathan Crowe

Reputation: 5803

Yes, there will be a (small) performance benefit to not calling the function over and over again. It is very minor so it really comes down to what is more readable and what you prefer.

I would do it like this:

$userId = Auth::check() ? Auth::user()->id : false;
$blogOwnerID = $blog->blogOwnerID;

// do my checks
if ($blogOwnerID === $userId) {
    // do something
}

make sure you are using === so you don't get false positives if $blog->blogOwnerID is 0

Upvotes: 1

Related Questions