1

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

3 Answers 3

2

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);
}

Sign up to request clarification or add additional context in comments.

4 Comments

@Maryam let me know if it helps.
I tested and it is not true
@Maryam Try now.
i think he is passing request wrong way. 'email','id' look at this.
0

import

use Illuminate\Support\Facades\DB;

and

if (isset($request->fields)) {
    $query = User::select(DB::raw($request->fields))->get();
}

Comments

0

Where does $resourceOptions['fields'] comes from?

You can use the array of items in the select function, like this:

if (isset($request->fields)) {
    $items = explode(',', $request->fields);
    $query = User::query();
    $query->select($items);
    $query->get();
}

Or like this

if (isset($request->fields)) {
    $query = User::query()->select(explode(',', $request->fields))->get();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.