Yes, the collection has the get()
method, which will return by key (which on eloquent colletions obv is the db primary key). This will only return data from the Collection so no query will be performed.
Ah! But can it return based on other attributes than the primary key?
You could use the filter()
method, but that could return more than one object. You could also just simply do
foreach ($users as $user)
{
if ($user->name === 'Peter')
{
$peter = $user;
break;
}
}
and probably lots of other ways. But it seems like a very strange way to do it. Why don't just do this in the DB?
Nice, thanks! Oh doing it with the DB is of course also an option, however in some cases, it feels like it would be unnecessary if I already had a collection where I know that the row already exists (e.g. users have already been fetched before in the method and been worked on in other ways, and now I want a specific user).
EDIT: Can't seem to mark any answer as the solution, but this is solved!
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community