$users = User::select('name')->get(); return $users->pluck('name')->toArray();
The select('name') limits the columns to 'name'. The get() returns a collection of User models with only the 'name' attribute. Using pluck('name') extracts the names into a simple array.
$users = User::select('id', 'email')->get(); return $users->first();
The select('id', 'email') tells Eloquent to only fetch those columns. The returned model instance will have only those attributes set.
Laravel's query builder supports specifying aliases directly in the select() method using the syntax 'name as username'. This generates the proper SQL alias and returns objects with the aliased property.
$users = User::select('id', 'email')->where('name', '=', 'Alice')->get(); return $users->email;
The get() method returns a collection, not a single model. Accessing $users->email causes an error because the collection does not have an 'email' property.
$users = User::select('id', 'name')->with('posts')->get();
The select('id', 'name') applies only to the main User query. The eager loaded 'posts' relationship runs its own query and loads all columns by default.