It's about Laravel Eloquent. I have a search filter programmed with four search criteria. Now it can happen that one or more search criteria are not specified.
Currently the query only works if all search criteria are present. But how I can do that when one or more search criteria are missing I have not found on the Internet search. Can you help me maybe?
$hours = Sap_cm01::join('production_supervisors', 'production_scheduler', '=', 'pr_superv')
->where('year', $selectedYear)
->where('cell', $selectedDepartment)
->where('area', $selectedValueStream)
->where('sap_cm01.ap', $apData)
->sum('val');
dd($hours);
I see 2 options to interpreter your question. The first is like @suhailparad metioned with an orWhere that means one of the criteria need to match.
It reads like: if year == selectedyear OR cell = selectedDepartment ...
$hours = Sap_cm01::join('production_supervisors', 'production_scheduler', '=', 'pr_superv')
->orWhere('year', $selectedYear)
->orWhere('cell', $selectedDepartment)
->orWhere('area', $selectedValueStream)
->orWhere('sap_cm01.ap', $apData)
->sum('val');
dd($hours);
The second way is how I read it. It can happen that not al the criteria are provided. Here is the when option useful (see: https://laravel.com/docs/8.x/queries#conditional-clauses )
It reads like: if year is provided then year == selectedyear AND if department is provided cell = selectedDepartment ...
$hours = Sap_cm01::join('production_supervisors', 'production_scheduler', '=', 'pr_superv')
->when($selectedYear, static function (Builder $yearQuery, $selectedYear): void {
$yearQuery->where('year', $selectedYear)
})
->when($selectedDepartment, static function (Builder $departmentQuery, $selectedDepartment): void {
$departmentQuery->where('cell', $selectedYear)
})
->when($selectedValueStream, static function (Builder $valueStreamQuery, $selectedValueStream): void {
$valueStreamQuery->where('year', $selectedValueStream)
})
->when($apData, static function (Builder $apDataQuery, $apData): void {
$apDataQuery->where('sap_cm01.ap', $apData)
})
->sum('val');
dd($hours);
I hope this can help you :)
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community