Answer the question
In order to leave comments, you need to log in
How to return the user who sent the message in Laravel?
Hi all! Such a situation. I have a model Dialog. It has messages() , a Message model, which in turn has a user() , a User model that returns the user who sent the message. I managed to return only the dialog along with the messages so far.
Question: How can I return in json the dialog, its messages and each user who sent the message.
$dialog = Dialog::with('messages')->where('id', $id)->get();
return response()->json([
'success' => true,
'dialog' => $dialog
]);
Answer the question
In order to leave comments, you need to log in
I would suggest something like this
if (number_in_range (stat['coef_tm_one_half'])) {
} else {
};
function number_in_range ($val) {
return ($val >= 1.33 && $val <= 1.6);
}
$dialog = Dialog::with(['messages', 'messages.user'])->where('id', $id)->get();
I tried it, it returns. But is it valid to do so or is there another way?
public function show($id)
{
$dialog = Dialog::where('id', $id)->with('messages')->get();
foreach ($dialog[0]->messages as $key => $message) {
$message['user'] = $message->user;
}
return response()->json([
'success' => true,
'dialog' => $dialog
]);
}
Request
In model
public function user() {
return $this->belongsTo(User::class);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question