Home > Back-end >  How to write a query conditionally in laravel?
How to write a query conditionally in laravel?

Time:02-09

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){
      
}

CodePudding user response:

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.

  •  Tags:  
  • Related