Reputation: 1983
... Either that or I'm not using / understanding it correctly. Take a look at my test snippet:
$subscriptions = auth()->user()->subscriptions()->get();
$id = '40';
$test = $subscriptions->filter(function ($subscription) use ($id) {
return $subscription->where('description_id', $id);
});
dd($test);
Currently there is one Subscription
in the database, with a description_id
of 20. When running the above test snippet, I still get the one result returned that has a description_id
of 20. So, this is not an expected result. What am I doing wrong?
Upvotes: 0
Views: 62
Reputation: 25414
where()
is used to filter a collection, but you're giving it a single subscription at a time when you use filter()
. And since where()
is also a method on an Eloquent model, what you're saying is essentially
Go through all subscriptions. For each one, start creating a SQL query. Unless that evaluates to false, keep the subscription in the list of all subscriptions.
Instead, what you mean to do is pretty close but not quite the same:
$test = $subscriptions->filter(function ($subscription) use ($id) {
return $subscription->description_id == $id;
});
Depending on what you want to do in practice, there may be other, more suitable methods as well. For instance, if you only want the first result since you only have a single id, then you can just replace filter
above with first
, and get the first matching subscription back rather than a collection of one subscription.
Upvotes: 1