5

For me it looks weird.

Cannot use object of type stdClass as array

I converted my query to array.

$query = DB::table('users')->where('name','=','Alex')->get()->toArray();

Checked my variable gettype($query); and it says Array.
Also checked it with var_dump($query); and it also shows Array.

So why while looping my $query in foreach I have to use $item->name and can't access to items as array $item['name'] ?

2
  • Could be an array of objects, not an array of arrays Commented Jan 10, 2018 at 12:56
  • @kerbholz yea, you are right. Thanks for an explanation Commented Jan 10, 2018 at 13:08

2 Answers 2

6

When you're using toArray(), you get an array of objects, so you still need to use:

$item->name

If you want to convert it to an array of arrays, do this:

$users = DB::table('users')->where('name', 'Alex')->get();
$users->transform(function($i) {
    return (array)$i;
});
$array = $users->toArray();
Sign up to request clarification or add additional context in comments.

1 Comment

Same issue, I always mix brackets and arrow. :) Thank you
-1

if you want to get result as array then use get()

$query = DB::table('users')->where('name','=','Alex')->get();

if you want to get result as object use first()

$query = DB::table('users')->where('name','=','Alex')->first();

4 Comments

get() returns a Collection of objects, so I still have to use ->, and first() returns only the first row
@qqmydarling , so what output you want ?
@qqmydarling , using get()->toArray(); is wrong , you are converting array to array , that is incorrect
as I said I was interested why I should access items as an object, but now I know. Thanks for a feedback. No, get() returns a collection of objects, not an array

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.