2

I want to add elements to each result of a SQL query:

$res = DB::table('users')->get();
forEach ($res as $elem) {
    $elem['new_data'] = 'this is my new data';
}

But I get this error on the line in the loop:

Cannot use object of type stdClass as array

How should I do that?

Thank you for your help.

5
  • 2
    it says in English that You're trying to use object of type stdClass as an array. so just replace $elem['new_data'] to $elem->new_data Commented May 11, 2018 at 16:50
  • I thought that only prototype oriented languages could do that. I can add properties dynamically to a class? Commented May 11, 2018 at 17:05
  • Actually it should. For example models which uses setAttribute method for that stuff. But for just stdClass I cannot predict, just give it a try. Commented May 11, 2018 at 17:09
  • Laravel has its own setAttribute function on its Model class. Well inherited from a trait, HasAttribute. IIRC, though, if you attempt to save that record with the new prop it'll throw a column not found error. Commented May 11, 2018 at 17:39
  • You are using DB and in question, you asked about Eloquent. If you use eloquent, you can create dynamic attributes and it will solve your problem like a charm. Try using Eloquent more instead of DB (suggestion). Commented May 11, 2018 at 18:51

2 Answers 2

4

You can use also laravel collection function https://laravel.com/docs/5.6/collections

$res = DB::table('users')->get();

$res = $res->map(function($user) {
  $user->new_data = 'this is my data'
  return $user;
}

dd($res)
Sign up to request clarification or add additional context in comments.

Comments

0

See the error message.

Cannot use object of type stdClass as array

$res is a collection of Objects

Use inside a foreach:

$elem->new_data

Insted of:

$elem['new_data']

$elem is not an array

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.