Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write a query conditionally in laravel?

I am new to the laravel, i am joining three tables based on conditions every thing is working fine but i need to write conditionally if the $field is array it should run with whereIn otherwise it should run where condition,can you please help me to acheive this thing

//$field sometimes it's an array sometimes it's a string.
public function find($field){
      
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For conditional constraints, you can use the when() clause:

$query = DB::table(...);

$data = $query
    ->when(is_array($field), function ($query) use ($field) {
        $query->whereIn('my_field', $field);
    }, function ($query) use ($field) {
        $query->where('my_field', $field);
    })
    ->get();

Now, as a tip, you could do this: Wrap the $fields variables to an array and then use always the whereIn clause. You can achieve this with the Arr::wrap() function:

use Illuminate\Support\Arr;

// ...

$query = DB::table(...);

$data = $query
    ->whereIn('my_field', Arr::wrap($field))
    ->get();

PS: I have linked the relevant functions to the docs so you can know how they work and their params.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading