laravel db pluck code example
Example 1: pluck array in laravel
$users = User::all()->pluck('field_name');
$user_ids = User::all()->modelKeys();
Example 2: when to use pluck method in laravel
When We should use Pluck method in laravel???
You might often run into a situation where you have to
extract certain values (excluding the keys) from a collection
then you should use pluck().
i.e (when you only need value, not the key)
let we have a list of results and we only need the value of one colum
$attendees = collect([
['name' => 'Bradmen', 'email' => '[email protected]', 'city' => 'London'],
['name' => 'Jhon Doe', 'email' => '[email protected]', 'city' => 'paris'],
['name' => 'Martin', 'email' => '[email protected]', 'city' => 'washington'],
]);
$names = $attendees->pluck('name')
OR You can use like this
$users = User::all();
$usernames = $users->pluck('username');
Example 3: how to pluck fullname database laravel
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
$agents = User::whereId($agent->id)->get()->pluck('full_name', 'id');
$agents = json_decode(json_encode($agents), true);