简体   繁体   中英

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.

You can do it like this:

$fields = ['field1', 'field2', 'field3'];

Model::select($fields)->get();

results:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM