samedi 1 octobre 2016

Relationship with user condition

I have a follow system that works like Twitter's follow (you follow other people and get updates from them).

I have this relationship set in my User.php model:

public function follows()
{
    return $this->hasMany('App\Follow');
}

This obviously gets all records of users who follow this person.

However, when displaying the person's profile page, I want to get a relationship that checks if a follow record exists given the user ID.

Something like:

public function userFollow()
{
    return $this->hasOne('App\Follow')->where('user_id', Auth::user()->id);
}

So now my profile page query looks like this:

$user = User::where('username', $username)
    ->with('userFollow')
    ->first();

This works as long as the user is logged in. If the user isn't logged in, the page gives me this error:

ErrorException in User.php line 28: Trying to get property of non-object

How do I fix this? What is the proper way of using conditions in relationships?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2dPnmrl
via IFTTT

Aucun commentaire:

Enregistrer un commentaire