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

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

/ 1000

I personally avoid using the dynamic/magic/fluent methods. I cannot remember my reasoning 😂

1

86

Yeah it depends on choice and what you prefer!

53

That’s awesome! I had no idea. I’ll give it a try in my next project

1

202

Glad you liked it!

54

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

I agree with @andrey but for different reasons. For me, Keeping it simple and more accessible compared to fancy is more importan

1

104

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();

1

143

Using Model has always been a better option.

92

Agree with you!

1

160

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

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

I like it!

155