MuZak
MuZak

Reputation: 301

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.

Upvotes: 3

Views: 5692

Answers (2)

N69S
N69S

Reputation: 17216

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

Upvotes: 4

Tharaka Dilshan
Tharaka Dilshan

Reputation: 4499

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

Upvotes: 1

Related Questions