0

I want to select from user table name and address columns where name is John. This query return null. I know in database is user which has name John. I would like to know if this query is property ?

 $query = User::where('name', '=', 'John')->select(['name', 'address']);
Shadow
  • 33,525
  • 10
  • 51
  • 64

4 Answers4

0
 $query = User::select('name', 'address')->where('name', '=', 'John')->first();

You were not running your query, you need get() which returns a collection or first() if you want to retrieve a single record.

For your case i think first() fits more.

Or following your approach you don't need select in the end but instead:

 $query = User::where('name', '=', 'John')->get(['name', 'address']);
pr1nc3
  • 8,108
  • 3
  • 23
  • 36
0

You can simply use this

$query = User::select('name', 'address')->where('name', '=', 'John')->first();
Dhaval Mistry
  • 476
  • 1
  • 9
  • 17
0

Just call get() at the end:

$query = User::where('name', 'John')->select(['name', 'address'])->get();

Notice: Maybe you're inaccurate in case sensitive. I mean the user name might be "john" not "John"

Alijvhr
  • 1,695
  • 1
  • 3
  • 22
0

You could use first(), which does the following:

  • limits the results to 1
  • get all records
  • get the first record from the collection

In the code, you will find:

public function first($columns = ['*'])
{
    return $this->take(1)->get($columns)->first();
}

Note that first() takes parameter which columns you want to select. So in your case, you can use:

User::where('name', '=', 'John')->first(['name', 'address']);

// Or a prettier solution in my opinion
User::whereName('John')->first(['name', 'address']);
Ron van der Heijden
  • 14,803
  • 7
  • 58
  • 82