Create eloquent query based on different criteria [Content needed]

1193 0 0 0

Last Updated : 2024-04-18 06:47:13

Sometimes, you need to make an Eloquent query that is modified by adding different parts based on other criteria. A typical good example of this is when you submit an advanved search form elements, Then you will need to create a query and then add the criteria based on the different inputs from the form.



$records = new LogvisitModel();
$records = $records->newQuery();

if(count($request->all())>0){
//return \'Search now\';
$dateFrom = $request->input(\'dateFrom\');
$dateTo = $request->input(\'dateTo\');
$userId = $request->input(\'userId\');
//----------------
if ($request->has(\'dateFrom\') && $request->input(\'dateFrom\') != \'\') {
$records->where(\'created_at\',\'>=\',$request->input(\'dateFrom\'));
}

if ($request->has(\'dateTo\') && $request->input(\'dateTo\') != \'\') {
//$records->where(\'created_at\',\'<=\',$request->input(\'dateTo\'));
$theDateTo = Carbon::createFromFormat(\'Y-m-d\', $request->input(\'dateTo\'));
$newDate = $theDateTo->addDays(1);
$newDate = Carbon::createFromFormat(\'Y-m-d H:i:s\', $newDate)->format(\'Y-m-d\');
$records->where(\'created_at\',\'<\',$newDate);
}

if ($request->has(\'userId2\') && $request->input(\'userId2\') != \'\') {
$records->where(\'user_id\',$request->input(\'userId2\'));
}
}else{
}


       

Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .