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...