hello world
hello world

Reputation: 13

return user model with eager loading laravel

 return $data =InteractiveSession::with('messages.user')->where('exercise_id',$exercise->id)->first();

This code will return data like below

{
"id": 1,
"exercise_id": 48,
"messages": [
    {
        "id": 1,
        "from_user": 69,
        "message": "Hi",
        "interactive_session_id": 1,
        "user": {
            "id": 69,
            "first_name": "Jobin"
        }
    }
]}

how can i return data like below??

{
"id": 1,
"exercise_id": 48,
"messages": [
    {
     "id": 1,
      "from_user":{
       "id": 69,
       "first_name": "Jobin"
        },
        "message": "Hi",
        "interactive_session_id": 1, 
    }
]}

i have tables interactivesession,message,users, using hasmany relation

Upvotes: 0

Views: 27

Answers (2)

matiaslauriti
matiaslauriti

Reputation: 8082

You can create a relation for from_user to the user model, and then do return $data = InteractiveSession::with(['messages.user', 'fromUser'])->where('exercise_id',$exercise->id)->first(); (remember fromUser should be your relation name)

Upvotes: 1

rfpdl
rfpdl

Reputation: 964

Try this:

$data = InteractiveSession::with('messages.user')->where('exercise_id',$exercise->id)->first();

$data->transform(function($record) {
    $messages = $record->messages->transform(function($message) {
        'id' => $message->id, 
        'from_user' => [
            'id' => $message->user->id,
            'first_name' => $message->user->first_name
        ],
        'message' => $message->message,
        'interactive_session_id' => $message->interactive_session_id
    });

    return [
        'id' => $record->id,
        'exercise_id' => $record->exercise_id,
        'messages' => $messages
    ];
});

Upvotes: 0

Related Questions