Courses

Laravel 11 Eloquent: Expert Level

Instead of Multiple If-Else, Use Eloquent When()

Summary of this lesson:
- Using when() for conditional queries
- Implementing dynamic query conditions
- Replacing if-else statements with when()
- Understanding conditional clause benefits

In Eloquent, there's an elegant syntax on how to write conditional queries. when the conditions depend, for example, on the request. Then you want to add where() statements dynamically.


In this example, we can have parameters user_id and is_completed from the GET request. The where() statement is added if either of these two parameters is present.

use App\Models\Task;
use Illuminate\Http\Request;
 
class HomeController extends Controller
{
public function index(Request $request)
{
$query = Task::query();
 
if ($request->has('user_id')) {
$query->where('user_id', $request->integer('user_id'));
}
 
if ($request->has('completed')) {
$query->where('is_completed', $request->boolean('completed'));
}
 
$tasks = $query->get();
 
foreach ($tasks as $task) {
dump($task->id . ': ' . $task->description);
}
}
}

Now, instead of making an if statement, we can use the when method on the Eloquent query. The first parameter must be the condition, and the second parameter is...

The full lesson is only for Premium Members.
Want to access all 28 lessons of this course? (71 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord