12728

don't get a sorted and clean result from get() function laravel Eloquent

Question:

The code below doesn't give me the correct result from the query.

<pre class="lang-php prettyprint-override">$studentMeta = StudentMeta::where([ 'meta_key' => 'brother_phone', 'students_id' => 9 ])->get(); print_r($studentMeta);

I get this result: <a href="https://i.stack.imgur.com/Gnu3u.png" rel="nofollow"><img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/Gnu3u.png" data-original="https://i.stack.imgur.com/Gnu3u.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" /></a>

However, I expect something like this:

$studentMeta => Array ( [id] => 49 [meta_key] => brother_phone [meta_value] => 7926161024 [created] => 2019-04-17 00:10:03 [students_id] => 9 )

Any ideas?

Answer1:

That's it because you are getting a collection of Model instances (because you are using get() instead of first() for example).

If you want to return it to the view, Laravel will call the ->toArray() method under the hood.

Try doind this to see your expected result:

$studentMeta = StudentMeta ::where(['meta_key' => 'brother_phone', 'students_id'=> 9]) ->get(); dd($studentMeta->toArray());

Check this section of the documentation: <a href="https://laravel.com/docs/5.8/eloquent-serialization" rel="nofollow">Eloquent Serialization</a>

Recommend