Home > front end >  How to call Variable Column name in Laravel MYSQL Select Query
How to call Variable Column name in Laravel MYSQL Select Query

Time:12-27

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?

CodePudding user response:

I think you can use the When eloquent function

$query = Images::query();

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

You can read more about it here.

CodePudding user response:

You were on the right track, the only issue you were having is that when the case is "private" it will load the column "title" twice, instead you can do the following:

if ($case == 'private') {
    $langtitle = ['id', 'title'];
}else{
    $langtitle = ['id', 'title', 'title_gov'];
}
Images::select($langtitle)->groupBy('id')->paginate('10');
  • Related