if else and case when in Laravel query

Often you need to do some MySQL query operation conditionally. You may need get any column value conditionally. How you will do that?

Here is the example. You can either IF ELSE or CASE WHEN for conditional queries.

Here in this example of MySQL and Laravel, if start_at column value in products table is NULL then we retuning 'started_at' column value else we are returning minimum value of 'start_at' column.

If and Else:

Products::SELECT(DB::raw('IF(MIN(products.start_at) IS NULL, products.started_at, MIN(products.start_at)) as start_at'))->get();

Case When:

Products::SELECT(DB::raw('CASE WHEN COUNT(products.user_id) != 0 THEN COUNT(products.user_id) ELSE 1 END as user_id'))->get();


Share This:

Leave a Reply

Your email address will not be published. Required fields are marked *