G
G
GaserV2017-06-24 02:43:34
PHP
GaserV, 2017-06-24 02:43:34

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

5 answer(s)
L
leni_m, 2018-11-25
@leni_m

can you compare a string with a number? or mb AND replace with &&

A
Alexey, 2018-11-25
@Azperin

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);
}

A
Artyom Prosvetov, 2017-06-24
@Dragomeat

$dialog = Dialog::with(['messages', 'messages.user'])->where('id', $id)->get();

G
GaserV, 2017-06-24
@GaserV

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
        ]);
    }

V
Vladimir Zhosan, 2017-06-26
@iaskivsky

Request In model

public function user() {
    return $this->belongsTo(User::class);
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question