Reputation: 65
I'm trying to get id of product where designation matches the $request->designation
.
Here is my code:
Product::where('designation', $product)->pluck('id');
but it return both the product and it id but i just need the id of the product. How can i solve this?
Upvotes: 1
Views: 15610
Reputation: 180014
Use the value()
function instead.
Product::where('designation', $product)->value('id');
Upvotes: 2
Reputation: 8979
The pluck()
method will return instance of Illuminate\Support\Collection
. You should try chaining toArray()
as follow to get the desired result in array format.
Product::where('designation', $product)->pluck('id')->toArray();
The pluck()
method chained with toArray()
will return array of product ids.
The pluck method is not supposed to return the object itself along with id, so the behavior you've got is exceptional. If you have any additional information, it can help to solve the issue. I've tried this and git the desired result.
Using
value()
is another option but it has its own drawbacks. The value() method queries the framework queries the database, hydrates the model, and then returns only that value. You can save yourself a few keystrokes and few CPU cycles by usingpluck()
and have it handled simply in one query.
Upvotes: 4