Maybe due to my Codeigniter background, I just don't find myself enjoying Laravel 4's Eloquent ORM a lot. Say I would like to write a query that order a list of posts by id, descending, how can Eloquent beat the clarity of DB::table('posts')->orderBy('id', 'desc')->get();
?
Is there a good reason to use Eloquent over Fluent, was it mostly for joining tables?
Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.
An web application always needs to interact with a database and Laravel makes this task hassle free. A few tools that make Laravel an awesome framework is the inclusion of “Query Builder and Eloquent ORM”.
Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.
It can be used to perform most database operations in your application and works perfectly with all of Laravel's supported database systems. The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks.
I came from codeigniter also and this is my experience: I use Eloquent and Fluent usually together. Eloquent is a thing that allows you to work nicely with relations, CRUD operations etc. When you need to do some SQL operations you can easily add some fluent functions
In the example you mentioned above I see you have posts table. If you have a post model then the same thing written using Eloquent is:
Post::orderBy('id', 'desc')->get();
So as I get it if you extends Eloquent than
Model_name::some_functions
is the same as
DB::table('table_name')->some_functions
The real power comes when you need to create or update a model, or, for example, get post comments. Than it becomes easily:
$comments = Post::find($id)->comments;
So the answer is - you have to use fluent functions to get ordered list. You can use them both with DB::table('posts')->orderBy or Post::orderBy
Using models and Eloquent, you can also write custom functions in your model class for performing common operations like, say, outputting a couple concatenated fields.
for instance:
<?php
class User extends Eloquent {
//Standard Relation Function
public function posts() {
return $this->hasMany('Post');
}
//Custom function
public function fullname() {
return $this->firstName.' '.$this->lastName;
}
}
//Somewhere else in your code, if you need a users full name...
$user = User::find(3);
$name = $user->fullname();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With