Laravel's belongsTo relationship
Greetings Pros,
I know this is easy for you guys but i'm really confused about this.
I have implemented a pagination ( which you can found in one of sir jeffrey's video activity feed is the video's name i think ) and etc...
Here's the relationship:
class Activity extends Eloquent {
//
public function user()
{
return $this->belongsTo('App\User');
}
public function subject()
{
return $this->morphTo()->withTrashed();
}
}
RecipientNumber Model
public function withDeletedRecipients() {
return $this->belongsTo('App\Recipient')->withTrashed();
}
Now i've deleted some recipient and for some point it displays an error saying:
Trying to get property of non-object (View: C:\wamp\www\textblast\resources\views\events\created_recipientnumber.blade.php) (View: C:\wamp\www\textblast\resources\views\events\created_recipientnumber.blade.php)
but when i include recipient_id in withDeletedRecipients
RecipientNumber Model
public function withDeletedRecipients() {
return $this->belongsTo('App\Recipient', 'recipient_id')->withTrashed();
}
It works perfectly. but if i remove the recipient_id it displays the error above.
Can someone enlighten me?
Thank you in advance.
@jake2025 You need the FK like @pmall said already. It will work with id (without any error to be precise), but it won't do what you want it to do. It will be completely wrong results.
Now, the error you're getting is simply caused by not checking whether relation exists (in your view), thus you get trying to get property of non-object error.
That said just add some check, like:
@if ($activity->recipient)
<p>{{ $activity->recipient->name }}</p>
@endif
Also withDeletedRecipients is definitely bad name. What does it tell you $activity->withDeletedRecipients if you're getting single related model here?
Please or to participate in this conversation.