Support the ongoing development of Laravel.io →
posted 3 years ago
Eloquent

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);

Last updated 2 years ago.
0

you are using AND WHERE condition, I instead you can use OrWhere

0
moderator

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 :)

suhailparad liked this reply

1

Sign in to participate in this thread!

Eventy

Your banner here too?

Veritexx veritexx Joined 19 Jan 2020

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.