O
O
ObehanProger2020-04-24 12:11:21
Laravel
ObehanProger, 2020-04-24 12:11:21

Why do related Eloquent model properties disappear when passed via ajax?

The Chat model has an associated Message model via an associated messages property:

public function messages(){
  return $this->hasMany(Message::class);
}

the controller finds a suitable chat and sends it back via Ajax
return $chat->firstOrCreate([
      'product_id' => $data['product_id'],
      'user_id' => $data['user_id']
]);

but when outputting the messages property, there is no:
$.get(
    "/chat/get_messages",
    {data:data},
    function (result)
    {
      console.log(result.messages);
    }
);

to output it is necessary to reassign this property in the controller:
$result= $chat->firstOrCreate([
      'product_id' => $data['product_id'],
      'user_id' => $data['user_id']
]);
$result->messages=$result->messages??null;
return $result;

This multiplies the code and is irrational. How to shorten or make the associated property not get lost

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Anton, 2020-04-24
@ObehanProger

https://laravel.com/docs/7.x/eloquent-relationship...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question