Search code examples
phplaraveleloquentlaravel-9

How to select fields according to input array in eloquent - laravel 9


$arr = array('field1', 'field2', 'field3');

From User Inputs I get array containing Field names. I have to fetch data from multiple table joins so, The goal is to select respective fields from tables according to table input from array.

    $update_co_column = Co_Total_Ia::
                      ->select(current($arr), next($arr), next($arr))
                     //->join('All Joins here')
                       ->where("user_key", "=", session()->get("user_id"))
                       ->where("student_details.deleted_at", "=", null);

I tried using PHP array methods, curret(arr) and next(arr). It is working, but just as an temporary solution. Problems in current solution -

  • Don't know exact how many fields to fetch
  • Need to fetch extra useless field all times.

Solution

  • You can do it like this:

    $fields = ['field1', 'field2', 'field3'];
    
    Model::select($fields)->get();
    

    results:

    SELECT
      `field1`,
      `field2`,
      `field3`
    FROM
      `model`