I have a few variables which I am receiving from a POST form, like so:
$search = $request->search;
$day = $request->day;
$month = $request->month;
$year = $request->year;
$status = $request->status;
In reality I have a bunch more, hence my question. I use these variables to query my database, using scopes. The way I am doing it now:
Chaining scopes:
$appointments = Appointment::latest('created_at')->search(search)->day($day)->month($month)->get(); // and so on..
But this only works if I use the following scopes:
public function scopeSearch($query, $date)
{
if($search)
{
return $query->whereDate('start', '=', $date);
} else {
return false;
}
}
Because with the above chaining method, if nothing was searched for, and I still directly return the query, no results are found, obviously. I changed my scopes like this:
public function scopeSearch($query, $value)
{
return $query->whereDate('condition', '=', $value);
}
But I would have to do the following in my controller:
$appointments = Appointment::latest('created_at');
if($day) {
$appointments = $appointments->month($day);
}
if($month) {
$appointments = $appointments->month($month);
}
if($year) {
$appointments = $appointments->month($year);
}
if($status) {
$appointments = $appointments->month($status);
}
$appointments = $appointments->get();
Yes, this works, but this is silly. Is there any way of doing this which I am not aware of yet? Should I be using a foreach for this instead perhaps or is there a cleaner, laravel way?