Back

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?

image

4

921

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.

2

241

Agree with you!

1

160

In response to @aniket

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"
]

2

126

  • No matching results...
  • Searching...

/ 1000

Got your point !

64

It is seems weird to me that eloquent manual is slower than eloquent magic
I thought it should be the opposite

1

75

I was sure of that too, but I executed the command a few times and always the magic was faster.... ┌(。Д。)┐

35