Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent ORM returning stdClass instead of Model instance

When I query data with eloquent, it returns stdClass objects instead of an instance of my Model when using the get() function.

$userFind = User::find(1)
$userGet  = DB::table('users')
            ->where('users.id','=', 1)
            ->select('users.*')->get()[0]

echo get_class($userFind) // -> App\User
echo get_class($userGet) // -> stdClass

Laravel Eloquent ORM returnig stdClass instead of actual Model reports the same problem but it is an old topic and the solution was just to come back to a previous version of Laravel.

like image 712
MuZak Avatar asked Feb 27 '26 16:02

MuZak


2 Answers

It's because you used \DB::table('users') which is independent from your models and code structure. It's like running a query directly on the database, laravel can't know that the result is a complete User with all it's fields.

use

$userGet = \App\User::query()
    ->where('id','=', 1)
    ->get()[0]
echo get_class($userGet) // -> App\User

//or simply
$userGet = \App\User::query()
    ->where('id','=', 1)
    ->first()
echo get_class($userGet) // -> App\User
like image 106
N69S Avatar answered Mar 02 '26 04:03

N69S


It's not because of using get()method. It's because of using DB facade.

If you query using model facade every objects will cast in to particular model object.

And the get()function will return an Eloquent Collection instead of a one Object.

// this is a collection of users
$users = User::where('id', 1)->get();

So if you want a one object from that collection you can call first() after it.
( instead of calling the array index [0] ).

// this one is ok too.
// but it's not recommended.
$user = User::where('id', 1)->get()[0];

// this is proper way
$user = User::where('id', 1)->get()->first();

And if you are sure that there is only one row matching your conditions you can call first() instead of get().

$user = User::where('id', 1)->first();
like image 40
Tharaka Dilshan Avatar answered Mar 02 '26 06:03

Tharaka Dilshan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!