Reputation: 2711
I have this relation, which contains reference to logged user
public function booksdislikedbyUser()
{
return $this->hasMany('Userattitude')->where('creator_id', Auth::user()->id)->selectRaw('count(IF(attitude = -1,0,1)) as dislikedbooks')->groupBy('entity_id');
}
My VIEW file which displays the output must be visible both for logged and unlogged user.
Problem: if user is not logged, I receive this error: Trying to get property of non-object
My question: what is best practice if I want to get the view and disable(?) the relation?
Option 1: What I am about to do is to put two variants of the code in IF - ELSE brackets.
if(Auth::check())
It works, but it doesn.t look like a good practice.
Option 2: in place of
->where('creator_id', Auth::user())
i would put
->where('creator_id', ($user_id ? $user_id : NULL))
Where I shoud define the variable then? $user_id = Auth::user()->id;
Upvotes: 0
Views: 87
Reputation: 153070
I'd go with Option 2.
public function booksdislikedbyUser()
{
$userId = (Auth::user() ? Auth::user()->id : null);
return $this->hasMany('Userattitude')->where('creator_id', $userId)->selectRaw('count(IF(attitude = -1,0,1)) as dislikedbooks')->groupBy('entity_id');
}
Or even simpler, use the Auth::id()
function:
return $this->hasMany('Userattitude')->where('creator_id', Auth::id())->selectRaw('count(IF(attitude = -1,0,1)) as dislikedbooks')->groupBy('entity_id');
Upvotes: 1