Table of contents
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 it helps. Thank you for reading.
Â
Happy coding :)
Read next