DEV Community

Cover image for Our way: Eloquent
Robson Tenório
Robson Tenório

Posted on • Updated on

Our way: Eloquent

👉 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()
Enter fullscreen mode Exit fullscreen mode

Nice!

User::query()
  ->with('some')
  ->whereHas('thing')
  ->where(...)
  ->orderBy(...)
  ->get()
Enter fullscreen mode Exit fullscreen mode

Nice!

// No problem if it is short
User::where('age', 18)->first();
Enter fullscreen mode Exit fullscreen mode

.
.
.

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();
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

.
.
.

The count()

WTF!?

// It loads ALL rows in memory, then count.
User::get()->count();
Enter fullscreen mode Exit fullscreen mode

Nice!

// Count inside database
User::count();
Enter fullscreen mode Exit fullscreen mode

.
.
.

The lazy()

WTF!?

// It loads ALL rows in memory, then starts loop
User::query()
   ->get()  // <-- here
   ->foreach(...);    

Enter fullscreen mode Exit fullscreen mode

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(...);    
Enter fullscreen mode Exit fullscreen mode

Nice!

// 99% of time you need this
User::query()->paginate(50);
Enter fullscreen mode Exit fullscreen mode

.
.
.

The when()

WTF!?

$results = User::where(...);

if($condition1){
   $results = $results->where('active', true);
}

if($condition2){
   $results = $results->where('age', '>=', 18);
}


return $results->get();

Enter fullscreen mode Exit fullscreen mode

Nice!

return User::query()
      ->when($condition1, fn($query) => $query->where('active', true))
      ->when($condition2, fn($query) => $query->where('age', '>=' 18))
      ->get();

Enter fullscreen mode Exit fullscreen mode

Top comments (0)