Updated April 11, 2023
Introduction to Laravel Pluck
The Laravel framework has been at the forefront of web development for some time. Over a period of time, it has become one of the most popular frameworks, primarily because of its easy to use queries and robustness. This also helps the framework to scale without much ado. The Laravel framework is also one of the most sought after framework for e commerce since it gives the client an immense range of functionalities to choose from. Laravel is also compatible with a whole lot of affiliated software, which helps set up entire systems.
Here in this article we are going to look into one such easy to use and yet a powerful query called the Laravel pluck().
How Does Laravel pluck() Work?
The Laravel pluck () as the name suggests, extracts certain values, as suggested. It literally plucks the information out from the given array and produces it as an output. However, it is most effective against objectives, but will work well against arrays too.
Example #1
The first one is by using one parameter. In this example, we see that the pluck mechanism is used on only one parameter. “name” in this case.
Code:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class getqueryController extends Controller
{
public function index(){
$names = DB::table('students')->pluck('name');
foreach ($names as $name) {
echo $name,"<br>";
}
}
}
Output:
Example #2
Now we would be working with two parameters:
Code:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class getqueryController extends Controller
{
public function index(){
$names = DB::table('students')->pluck('name','id');
foreach ($names as $id=>$name) {
echo "ID: ", $id;
echo " Name: ", $name,"<br>";
}
}
}
Output:
If you see carefully, we have used two parameters, namely “id” and “name”. Hence, when we get the output, we get two columns.
What the pluck () function does is that it essentially loops through a collection and collects all the data from the particular field and stores it in another collection. That would mean, it plucks the concerned value from a large set of data and stores them in a separate collection for later usage.
Syntax:
$userIds = User::all()->pluck('id');
// $userIds now contains a collection of all user ids in that collection or table
Example #3
Code:
$collection = collect([
["name" => "person", "id" => 1],
["name" => "another person", "id" => 2]
]);
$names = $collection->pluck("name");
$names->all(); // ["person", "another person"]
note that Laravel pluck () is not limited to Eloquent collections only. It can be used on any Laravel collection.
You may go further and want an associative array instead of just the plucked items. In order to specify how the collection that is returned needs to be keyed, we make the second argument the key to the pluck function:
$collection = collect([
["name" => "person", "id" => 1, "occupation" => "student"],
["name" => "another person", "id" => 2, "occupation" => "developer"]
]);
$names = $collection->pluck("name", "occupation");
$names->all();
Output:
Also, points to remember is the presence of a duplicate value. While using a pluck () function, if such a data exists, the item which last matches the key, gets returned.
$fruits = collect([
["name"=> "mango", "status"=> "ripe"],
["name"=> "banana", "status"=> "ripe"],
["name"=> "apple", "status"=> "unripe"],
["name" => "grape", "status"=> "unripe"],
["name" => "pineapple", "status"=> "rotten"]
]);
$fruits->pluck('status', "name");
$fruits->all();
Output:
Example #4
Using pluck() to extract values of only one column:
$title = $collection->pluck('title');
$title->all();
Output:
While developing in eloquent, the column name can be passed as an argument in order to extract the values.
Pluck () also accepts a second argument and if it happens to be an Eloquent collection, it will be another column name.
$title = $collection->pluck('user_id', 'title');
$title->all();
Output:
To further strengthen the pluck() function, the wherein() function can be used.
Example #5
Code:
$food = collect([
["name" => "Rice & pepper soup", "type" => "African dish"],
["name" => "Egusi soup", "type" => "African dish"],
["name" => "Sharwama", "type" => "Junk"],
["name" => "Pizza", "type" => "Junk"],
["name" => "Coke", "type" => "Drink"],
["name" => "Coffee", "type" => "Drink"],
]);
$junk = $food->whereIn('type', ['Junk', 'Drink']);
$junk->all();
Output:
The above examples are testament to the flexibility of the query. We used the wherein() function in conjunction with the pluck() query to get our desired results. The pluck() function is a multi-faceted command set which pulls out the most relevant information and yet works in tandem with other associated queries too.
The pluck () function is a helpful function because it picks out the relevant information from a large set of data. It is easy to use and can also be modified as per the requirement. The above examples are an example of how parameters can be changed to change outputs.
To get the correct output, it is hence imperative to correctly define the key and value. Only then will the query be able to identify the information and store it in another collection. For multiple values, separate collections will have to be used to generate the correct output.
Conclusion
- With the above examples we have been able to confirm the efficacy of the function, pluck (). It not only is able to generate the required output but goes along well if combined with other functions, like wherein () too. This is also the hallmark of the laravel framework which allows its queries to be simple to use and yet flexible enough for collaborative effect.
- It does not break form even if additional parameters are inserted to pull out more information. Prime examples being more number of columns added to the output result.
- With pluck () we now have a ready to use query which accelerates the development procedure without breaking much sweat. The above article is replete with examples regarding the same.
Recommended Article
We hope that this EDUCBA information on “Laravel Pluck” was beneficial to you. You can view EDUCBA’s recommended articles for more information.