Q:

How to generate a dynamic mysql query in laravel?

I would like the users to choose which fields they want to see and which ones they don't.This is my API URI which is a get request.
/api/v1/admin/users/1?fields=email,id

This is my code  :
if (isset($request->fields)) {
            $temp = null;
            $items = explode(',', $request->fields);
            foreach ($items as $item) {
                $temp = $temp . "'" . $item . "',";
            }
            $fields = trim($temp, ',');

            $query = User::query();
            $query->select($resourceOptions['fields']);
            $query->get();
        }

but I got this error:
"SQLSTATE[42S22]: Column not found: 1054 Unknown column ''email','id'' in 'field list' (SQL: select `'email','id'` from `users` where `users`.`deleted_at` is null)"

Any help (or if someone can point me towards a good tutorial) would be greatly appreciated!
Thanks

A:

In laravel you can add query with where() clause. But in your case. It's not required.
Just run this.
if (isset($request->fields)) {
        $users = User::select(DB::raw($request->fields))->get();
        dd($users);
}

