skip to Main Content

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?

2

Answers


  1. 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');
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search