👉 Go to Summary
There is no wrong or right way, there is our way.
-- Someone
.
.
.
One method per line
WTF!?
User::with('some')->whereHas('thing')->where(...)->orderBy(...)->get()
Nice!
User::query()
->with('some')
->whereHas('thing')
->where(...)
->orderBy(...)
->get()
Nice!
// No problem if it is short
User::where('age', 18)->first();
.
.
.
The scopeXXXX()
WTF!?
$activeUsers = User::where('active', true)->get()
// Same `active` logic
$activeAgedUsers = User::query()
->where('active', true)
->where('age', '>=', 60)
->get();
// Same `active` and `age` logic
$activeAgedMaleUsers = User::query()
->where('active', true)
->where('age', '>=', 60)
->where('gender', 'male')
->get();
Nice!
$activeUsers = User::active()->get();
$activeAndAgedUsers = User::active()->aged()->get();
$activeAgedMaleUsers = User::active()->aged()->male()->get();
public function scopeAged(Builder $query): Builder
{
return $query->where('age', '>=', 60);
}
public function scopeMale(Builder $query): Builder
{
return $query->where('gender', 'male');
}
public function scopeActive(Builder $query): Builder
{
return $query->where('active', true);
}
.
.
.
The count()
WTF!?
// It loads ALL rows in memory, then count.
User::get()->count();
Nice!
// Count inside database
User::count();
.
.
.
The lazy()
WTF!?
// It loads ALL rows in memory, then starts loop
User::query()
->get() // <-- here
->foreach(...);
Nice!
// Do it only if you really need to check ALL rows
// It loads chunked results and start loop immediately
User::query()
->lazy() // <-- here
->foreach(...);
Nice!
// 99% of time you need this
User::query()->paginate(50);
.
.
.
The when()
WTF!?
$results = User::where(...);
if($condition1){
$results = $results->where('active', true);
}
if($condition2){
$results = $results->where('age', '>=', 18);
}
return $results->get();
Nice!
return User::query()
->when($condition1, fn($query) => $query->where('active', true))
->when($condition2, fn($query) => $query->where('age', '>=' 18))
->get();
Top comments (0)