1

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,
    ...
])
5
  • 1
    Yes, use ->select('email','password') Commented Jun 26, 2015 at 8:15
  • So instead of first() I use select(...) ? Commented Jun 26, 2015 at 8:15
  • 1
    no you add select as a function on the query before you get the results (with ->first() ) laravel.com/docs/4.2/queries#selects Commented Jun 26, 2015 at 8:16
  • I have added answer... Commented Jun 26, 2015 at 8:19
  • Do you get solution? @Arbitur Commented Jun 26, 2015 at 8:27

2 Answers 2

2

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.

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

4 Comments

Thanks, so there is only option to select which, and not which to ignore?
Actually this is the proper way to select data from the database... This similar to SELECT query
Yes but just wondering if I would add a column later and dont have to add that column in my source aswell. Maybe Ill have to make a custom function for that?
You will add column in future and don't want to add your source means you just select * from the db, then use it in view by column name. I don't know your question has solution.
1

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

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

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.