Laravel Pluck Method Example
source link: https://www.laravelcode.com/post/laravel-pluck-method-example
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Laravel Pluck Method Example
Sometimes, you may want only one column from the database as array. Laravel provides easy way to get single column value from database. Laravel collection pluck() method only returns the selected column.
In this article, I will share you how you can use Laravel pluck() method.
When generating list or select dropdown from database, pluck() method helps a lot.
Suppose we have countries collection array as below.
$countries = collect([
['name' => 'Afghanistan', 'code' => 'AF'],
['name' => 'Albania', 'code' => 'AL'],
['name' => 'Algeria', 'code' => 'DZ'],
['name' => 'Andorra', 'code' => 'AD'],
['name' => 'Angola', 'code' => 'AO']
]);
Now we need only country name field. Let's take example below:
$country_name = $countries->pluck('name');
This will return only country name from the collection.
[
"Afghanistan",
"Albania",
"Algeria",
"Andorra",
"Angola"
]
Now we can use this list in the blade view using foreach loop.
<ul>
@foreach ($country_name as $name)
<li>{{ $name }}</li>
@endforeach
</ul>
Now suppose we want to generate select dropdown with key and value pair. We can get this by passing second parameter as key field.
$country_name = $countries->pluck('name', 'code');
This will return name and code key-value pair.
[
"AF" => "Afghanistan",
"AL" => "Albania",
"DZ" => "Algeria",
"AD" => "Andorra",
"AO" => "Angola"
]
Now you can simply loop through array into dropdown like this:
<select name="country">
@foreach ($country_name as $key => $name)
<option value="{{ $key }}">{{ $name }}</option>
@endforeach
</select>
This way, you can use Laravel collection pluck() method. I hope you liked this article.
Author : Harsukh Makwana
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK