In this post explain of Laravel pluck example. You will easily learn about Laravel pluck method example. I will share how to pluck method in Laravel. You can understand a concept of db query pluck method.
How to use the pluck method in Laravel
The pluck method in Laravel is simple yet powerful concept used to extract values from a collection or database query. You want to retrieve a single column’s values from a dataset. Here’s you can get simple example.
What is pluck method?
The pluck method is used to fetch a specific value key-value pair from database set. It return the values as an array or collection.
Syntax:
Model::pluck('column_name');
Example of using pluck
1. Extract a single column using pluck method in Laravel
You can use the pluck method to retrieve values of a single column from the database.
public function index()
{
$users = User::pluck('id');
dd($users);
}
Output:
#items: array:1 [▼
0 => 1
]
2. Extract key-value pairs using pluck method in Laravel?
You can specify a second argument to get key-value pairs.
public function index()
{
$users = User::pluck('status', 'id');
dd($users);
}
Output:
#items: array:1 [▼
1 => "deactive"
]
Why use pluck?
- Simplifies data extraction.
- Optimize query selecting only required column.
- Reduce additional processing or transformation of data.
By using pluck method, you can simplify data manipulation and improve performance your task.
I hope this tutorial help you.