How to call Variable Column name in Laravel MYSQL Select Query

My concern:

if ($case=='private') {
    $langtitle = 'title';
    }
else {
     $langtitle='title_gov';
    }

if it is Government (falls under else case above) I want to select, 'title' as well as 'title_gov' with Select in query as,

Images::select($langtitle ,'id', 'title')
            ->groupBy('id')
            ->paginate('10');

If it is private, then only 'title' to be selected. I do not want to use if else case for Query, instead I want to call it using Variable or regex or some method. How can I?

>Solution :

I think you can use the When eloquent function

$query = Images::query();

$query->when($case == 'private', function ($q) {
return $q->select('title' ,'id');
}, function ($q) {
return $q->select('title_gov' ,'id','title'));
})->groupBy('id')
  ->paginate('10');

you can read more about it here

Leave a Reply