How to create Eloquent models from Laravel Query Builder results

Sometimes Eloquent doesn’t provide all of the functionality and access to data that you need out of the box. Even Taylor Otwell, the framework’s creator, often uses query builder for his DB operations.

Getting wet

Refer to the the query builder docs on how to use it: Query Builder

Running a query such as: \DB::table('users')->take(2)->get(); will return an array of stdClass objects.
What if you want to change those into User model objects? Just use the hydrate() method that is on every Eloquent model and it will give you back a collection of User models:

$result = \DB::table('users')->take(2)->get();
$users = \App\Users::hydrate($result); 

Illuminate\Database\Eloquent\Collection {#888
     all: [
       App\User {#886
         id: "1",
         role_id: "1",
         name: "Nicole Pfeffer",
       },
       App\User {#884
         id: "2",
         role_id: "1",
         name: "Stephanie Wilkinson MD",
       },
     ],
   }

Be careful though, if you get results from another table you can hydrate those as an object that they are not. For example, if you get results from a posts table and then hydrate them as a User object it will work. With great power comes great responsibility as they say.

Written on October 25, 2015