Wednesday, March 8, 2017

Return null from eloquent relationship?

I have this relationship in one of my model classes:

public function userLike()
{
    if (Auth::check()) return $this->hasOne('App\Like')->where('user_id', Auth::user()->id);

    // RETURN NULL IF RECORD DOESN'T EXIST?
}

As you can see, it checks if the user is logged in and returns the Like record. However, how can I return null if the record doesn't exist?

I tried this:

public function userLike()
{
    if (Auth::check()) return $this->hasOne('App\Like')->where('user_id', Auth::user()->id);

    return null;
}

But I get the error:

local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to a member function addEagerConstraints() on null' in /var/www/social/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:680

As a side question, am I doing this right? Is this the correct way of doing this or is there a better way?



via user7680802

Advertisement