0

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.

1
  • array and collection are treated differently. Commented Sep 19, 2022 at 7:13

3 Answers 3

1

Convert it into a collection and push into it

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

Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.