Reputation: 10828
Is there any advantages of using Laravel Eloquent all the time instead of raw SQL?
I have a habit of writing SQL first in phpMyAdmin to check the relationship and then translate it Eloquent ORM.
Sometime translating to Eloquent ORM is painful and time consuming especially translating from long complicated SQL query. I am able to write fast in SQL than using Eloquent ORM.
Upvotes: 3
Views: 424
Reputation: 44526
The most important benefit of using the Query Builder is abstraction, which usually leads to less code. Also, because the builder is database agnostic, it allows to seamlessly switch the RDBMS, for example from MySQL to PostgreSQL (but this only applies in some cases as there are some things that are database specific and cannot be abstracted).
Using it in conjunction with Eloquent offers the added benefit of having the results converted into Eloquent models, which means you can use relations, mutators, accessors and all the other benefits that Eloquent models offer. For example:
$users = DB::select('select * from users');
Will return an array of stdClass
objects, while the following:
$users = User::all();
Will return a collection of Eloquent models on which you can get relations:
foreach ($users as $user) {
$user->projects();
}
Or make changes and save the entry:
$user->name = 'Bob Dylan';
$user->save();
These things can be done with the raw query approach, by manually creating a collection of models like so:
// Replace the stdClass items with User models
foreach ($users as &$user) {
$user = new User($user);
}
// Create a Collection with the results
$users = new Illuminate\Support\Collection($users);
But it adds complexity which is already implemented by Eloquent.
A good example of how abstraction leads to less code would be this:
User::whereIn('id', [1, 7, 100]);
Which is less code than the equivalent:
DB::select('select * from users where id in (?)', [implode(',', [1, 7, 100]);
The important thing to take in consideration when using raw queries that make use of user input, is to always use bindings to avoid leaving yourself open to SQL Injection.
That being said, there are cases where, as you said, it's a pain to convert queries to use the Query Builder, because the builder has limitations given that it's database agnostic.
There is no problem with using raw queries. I usually use a combination of both Query Builder for simpler queries that need Eloquent models and raw queries for more complex operations, where it just makes sense not to use DB::raw
allover the place just to use the Query Builder. So taking into account the things I said above, it just boils down to preference really.
Upvotes: 5
Reputation: 4774
There's no problem and you should use raw SQL if that suits you better. Eloquent's goal is to simplify queries.
The only thing you have to take care of is to prepare everything.
Upvotes: 0