Arbitur
Arbitur

Reputation: 39091

Laravel DB select only/except?

I have this line:

$user = DB::table("users")
            ->where("email", $email)
            ->where("password", $password)
            ->first();

This selects all columns. Is there a way to discard or pick which columns to fetch or do I have to add each column I want to respond with manually? Like Request only() and except() methods.

Manual way:

response()->json([
    "name" => $user->name,
    ...
])

Upvotes: 1

Views: 1729

Answers (2)

Md Adil
Md Adil

Reputation: 307

You can pass an array in the first method with each field name you want to get.

->first(['field1', 'field2']);

Upvotes: 1

Praveen Srinivasan
Praveen Srinivasan

Reputation: 1620

This will get selected column....

$user = DB::table("users")
        ->select('name')
        ->where("email", $email)
        ->where("password", $password)
        ->first();

or

$user = DB::table("users")
        ->select('name')
        ->where("email", $email)
        ->where("password", $password)
        ->get();

you can return this result as json as follows

return Response::json($user);

For this you should add the controller use Response on the top.

Upvotes: 2

Related Questions