Reputation: 1281
I've been trying out Laravel 5 as an alternative to a Spring boot set up.
$employees = App\Employee::all();
$employees = DB::table('employees')->get();
I've read up that these two lines of code do the exact same thing, retrieve all the records from my 'employees' table. This is true to some extent, however the first line, although more succinct and clean, provides a much more verbose and nested collection representing the same number of records
Employee {#180 ▼
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:3 [▶]
#original: array:3 [▶]
#casts: []
#dates: []
#dateFormat: null
#appends: []
#events: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
vs
{#173 ▼
+"id": 3
+"username": "deren"
+"password": "noob"
}
For the first collection, the identical information to the second collection is contained within original. What's the difference between the two and why does the first query via Eloquent contain far more metadata? I feel like it contradicts the eloquence (pardon the pun) that it provides, especially considering I have no idea how to access the array within original. I'm using dd() to dump the variable containing the collection if that makes a difference.
Upvotes: 0
Views: 28
Reputation: 778
$employees = App\Employee::all();
This reads the database table, turns each row into an instance of the specific model class and returns them with all their added properties, methods, etc..
$employees = DB::table('employees')->get();
This reads the database table and turns each row into a standard class. It has no knowledge of the models.
Upvotes: 3