Hey Laravel Developers
Did you know that when adding where conditionals in the Query Builder, you can use dynamic method names?
For example, if you want to fetch an order matching a particular quantity, you can call a dynamic method like whereQuantity($quantity) instead of using where('quantity', $quantity).
It just reads so much better! What do you think?
I personally avoid using the dynamic/magic/fluent methods. I cannot remember my reasoning 😂
Personally, I try to avoid using dynamic because due to the large amount of processed information in general, it can put a heavy load on the CPU, so the query will be processed much slower.
So you have to choose between beauty and performance. In this case I choose the second one.
I agree with @andrey but for different reasons. For me, Keeping it simple and more accessible compared to fancy is more importan
If we take a specific code example from the topics, I would prefer to write it like this:
$order = DB::table('orders')
->where(compact('quantity'))
->first();
And it is even better to use the Order model instead of direct reference to the table at least because in case of anything you will have to search through the code for all references to this table instead of Ctrl+Click on the class name.
$order = Order::query()
->where(compact('quantity'))
->first();
Let's check it:
1. Create a new app
laravel new test --api -n
cd test
2. Put a new console command to `routes/console.php` file:
use App\Models\User;
use Illuminate\Support\Benchmark;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
Artisan::command('foo', function () {
Benchmark::dd([
'eloquent manual' => fn () => User::query()->where('name', 'foo')->first(),
'eloquent magic' => fn () => User::query()->whereName('foo')->first(),
'db manual' => fn () => DB::table('users')->where('name', 'foo')->first(),
'db magic' => fn () => DB::table('users')->whereName('foo')->first(),
], iterations: 1000);
});
And, I don't know why there is such a difference in the case of Eloquent, but here is my result:
array:4 [
"eloquent manual" => "0.267ms"
"eloquent magic" => "0.252ms"
"db manual" => "0.149ms"
"db magic" => "0.151ms"
]
It is seems weird to me that eloquent manual is slower than eloquent magic
I thought it should be the opposite
I was sure of that too, but I executed the command a few times and always the magic was faster.... ┌(。Д。)┐