Home > Mobile >  How to add object to existing Laravel Query?
How to add object to existing Laravel Query?

Time:09-20

What I want to do is add an object to the existing query.

This is my work in progress right now:

$users = ModelUser::where('date_created', $date)->get();

foreach($users as $user){
  $obj = ['test1'=> 'val1','test2' => 'val2','test3'=> 'val3',];
  $users['items'] = $obj;
}
return $users;

what I'm hoping is a result is like this.

{"username":'Username1', "Fname":'fname1', "items":['test1' = 'val1','test3' = 'val3','test3' = 'val3']
"username":'Username2', "Fname":'fname2', "items":['test1' = 'val1','test3' = 'val3','test3' = 'val3']
"username":'Username3', "Fname":'fname3', "items":['test1' = 'val1','test3' = 'val3','test3' = 'val3']
"username":'Username4', "Fname":'fname4', "items":['test1' = 'val1','test3' = 'val3','test3' = 'val3']
}

Where the items are like in a sub object.

CodePudding user response:

Just to understand a bit more, does the "items" element you want to add to the user object have any relationship at the database level? If so, it would be better to define a relationship within the ModelUser https://laravel.com/docs/9.x/eloquent-relationships#defining-relationships

In case not, I see you're using a $user as an array, but actually $user is a ModelUser element. So a trick, definitely not recommended, would be:

$user->items = $obj;

CodePudding user response:

Convert it into a collection and push into it

https://laravel.com/docs/9.x/collections#method-push

CodePudding user response:

You can use laravel map as

$users = ModelUser::where('date_created', $date)->get();

will return a collection. So your expected code will be something like the following

 $users = $users
    ->map(function ($user) use ($obj) {
         return $user->items = $obj;
      })
    );
  • Related