prgrm
prgrm

Reputation: 3835

Returning a single Eloquent object in Laravel

I have this function:

protected function compare_something($found_item, $saved_items)
{
foreach($saved_items as item) {

$compare_x = false;
$compare_y = false;
$compare_z = false;

$compare_x = strpos($found_item,$item->x) !== false ? true: false;
$compare_y = strpos($found_item,$item->y) !== false ? true: false;
$compare_z = strpos($found_item,$item->z) !== false ? true: false;

if($compare_x && $compare_y && $compare_z){
return $item;
}

}
return false;
}

I expect $item to be the object where $compare_x, $compare_y and $compare_z are true, however this function simply returns the entire eloquent object ($saved_items) instead of the compared one.

I am not sure why is this happening. I can always return:

$item->id

And then do Item::where("id",$item->id)->first();

But shouldn't just return $item just deliver me the chosen item?

Upvotes: 1

Views: 965

Answers (1)

Jerodev
Jerodev

Reputation: 33206

Eloquent queries always return a collection, so you can easily use the filter function for this. After that call the first function to get the first element. If there are no elements in the collection, null will be returned.

For example:

return $saved_items->filter(function ($item) use ($found_item) {
    return strpos($found_item, $item->x) !== false &&
           strpos($found_item, $item->y) !== false &&
           strpos($found_item, $item->z) !== false;
})->first();

Upvotes: 4

Related Questions