Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Query where column is specific value or any value

Tags:

mysql

laravel

Not specifically a Laravel question, but I am using Laravel Query Builder. I have a MySQL database column that contains any one of a long list of statuses. When filtering the list I simply pass the status or statuses as an array to the query...

$statusArray = ['active','inProgress'];

DB::table('mytable')->whereIn('status', $statusArray)->get();

However when not filtering I want all statuses returned so I would wish for something like...

 $statusArray = [*];

Is there a simple way to handle this or do I need to dynamically build the whereIn clause for the query?

like image 948
skribe Avatar asked Dec 02 '25 22:12

skribe


2 Answers

When you want to see perticular status add them in $statusArray

$statusArray = ['active','inProgress'];

And when you want to get all statuses declare $statusArray as empty array

$statusArray = array();

Then add condition in eloquent like below

DB::table('mytable')->when(!empty($statusArray), function($q, $statusArray) {
   return $q->whereIn('status', $statusArray);
})->get();
like image 102
Leena Patel Avatar answered Dec 04 '25 17:12

Leena Patel


Yo can use the 'when' conditional clause. This will help you add additional conditions to your query when a condition is satisfied and skip the conditions when it is not. (in your case, when the filter is to be applied

See here : https://laravel.com/docs/5.7/queries#conditional-clauses

like image 30
pseudoanime Avatar answered Dec 04 '25 17:12

pseudoanime



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!