Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading