Foued MOUSSI
Foued MOUSSI

Reputation: 4813

Laravel : Conditional select columns using Elequent

I'm trying to get columns with some if conditions like "if column is null, get other column instead".

My current code

$products = Product::whereHas('images', function($q) {
    $q->where('published', 1)
})->get(['id as value', 'product_short_name as label']);

Need to make it like

if prdouct_short_name is Null get me product_name as label

Upvotes: 0

Views: 1009

Answers (1)

112Legion
112Legion

Reputation: 1237

If you are using MySQL you can try to use rawSelect.

Product::whereHas('images', function($q) {
    $q->where('published', 1)
})->selectRaw('id as value, IF (product_short_name IS NULL, product_name, product_short_name) as label')->get();

Upvotes: 2

Related Questions