Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/laravel/laravel-8-eloquent-pluck-example
Laravel 8 Eloquent pluck() method helps us to extract certain values into 1 dimension array. It shortens our code if we want only to get the specific field values into 1 dimension array so that we don't need to loop the result collection to get certain values using this method. In this post, we are using a posts table with title, description, and body fields.
In this example, we want to display the title only into 1 dimension array. Or should be like this:
Array
(
[0] => Post 3
[1] => Post 1
[2] => Post 2
[3] => Post 3
[4] => Post 4
)
But to do that in we need to use all() method in eloquent as you can see in the following below:
$posts = Post::all();
$postsTitles = [];
foreach($posts as $post) {
$postsTitles[] = $post->title;
}
print_r($postsTitles);die;
As you can see above we loop the post result then we store the post title to our array variable which is not good because our code is long.
And the result is the same:
Array
(
[0] => Post 3
[1] => Post 1
[2] => Post 2
[3] => Post 3
[4] => Post 4
)
But using the pluck() method in Laravel our code will be short. See the below example:
$posts = Post::all()->pluck('title')->toArray();
print_r($posts);die;
And the result is the same above:
Array
(
[0] => Post 3
[1] => Post 1
[2] => Post 2
[3] => Post 3
[4] => Post 4
)
I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/laravel-8-eloquent-pluck-example if you want to download this code.
Happy coding :)
Top comments (1)
Good tip, but it can be better in performance using