skip to Main Content

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']);

4

Answers


  1.  $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']);
    
    Login or Signup to reply.
  2. You can simply use this

    $query = User::select('name', 'address')->where('name', '=', 'John')->first();
    
    Login or Signup to reply.
  3. 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"

    Login or Signup to reply.
  4. 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']);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search