DEV Community

Cover image for Laravel 8 Eloquent pluck() Example
Code And Deploy
Code And Deploy

Posted on

Laravel 8 Eloquent pluck() Example

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
)
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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
)
Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

And the result is the same above:

Array
(
    [0] => Post 3
    [1] => Post 1
    [2] => Post 2
    [3] => Post 3
    [4] => Post 4
)
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
gregorip02 profile image
Gregori Piñeres

Good tip, but it can be better in performance using

Post::pluck('title')->toArray();
Enter fullscreen mode Exit fullscreen mode