Reputation: 59
I would like to display users that have sent or got message/s.
User Model:
public function messages_sender()
{
return $this->hasMany('App\Message', 'sender_id');
}
public function messages_recipient()
{
return $this->hasMany('App\Message', 'recipient_id');
}
MessageController
public function index()
{
$users = User::with('messages_recipient', 'messages_sender')->paginate(5);
//return $users;
return view('message.index',compact('users'));
}
Messages View:
{{ $user->messages_recipient['recipient_id'] }}
Result is an error in view "Undefined index: recipient_id" or when i try to access any of them (sender_id, recipient_id). I understand that not all users have messages, as i see in JSON format, so i used:
@if($user->messages_recipient->has('recipient_id'))
{{ $user->messages_recipient['recipient_id'] }}
@endif
and than error did not show.
JSON: https://pastebin.com/NFSWMp7r
As I am new to Laravel i could use some help. In similar example it worked when I needed to get users and name of their role (admin, user).
Upvotes: 1
Views: 1325
Reputation: 2401
Your using the message_recipient as an array and if a key doesn't exist on an array PHP will always throw an error. The hasMany relationship returns a Collection of Message objects so you would need to use it as an object with:
@foreach($user->messages_sender as $message)
{{ $message->id }}
@endforeach
and
@foreach($user->messages_recipient as $message)
{{ $message->id }}
@endforeach
or if you just wanted all of the message ids you could do $user->messsages_recipient->pluck('id')
and that would return all of the ids of the Message objects.
Upvotes: 0
Reputation: 106
You can access the Users form the App\Message
Model instead of the other way round.
Message Model:
public function senders()
{
return $this->belongsTo('App\Users', 'sender_id');
}
Message Controller
public function index()
{
$senders = Message::senders()->paginate(5);
return view('message.index',compact('senders'));
}
Dont blame me but I am not sure, if the sender_id
is just right there :-P
Unfortunately, if you want unique records this will not work.
Upvotes: 0