Yes, there is a way to remove a model from a collection by passing the model itself to a function. You can achieve this by creating a custom method in your collection class.
Here's an example of how you can implement this:
use Illuminate\Database\Eloquent\Collection;
class CustomCollection extends Collection
{
public function removeByModel($model)
{
$this->items = $this->reject(function ($item) use ($model) {
return $item->getKey() === $model->getKey();
})->values()->all();
}
}
In this example, we extend the Illuminate\Database\Eloquent\Collection class and add a new method called removeByModel. Inside this method, we use the reject method to filter out the model from the collection based on its primary key. Finally, we use the values method to reset the keys of the collection.
To use this custom collection, you need to replace the default collection class with your custom class in your model. For example:
use App\CustomCollection;
class User extends Model
{
public function newCollection(array $models = [])
{
return new CustomCollection($models);
}
}
Now, you can use the removeByModel method on your collection of models:
$users = User::all();
$userToRemove = User::first();
$users->removeByModel($userToRemove);
After executing this code, the $users collection will no longer contain the first user.
Note: This solution assumes you are using Laravel's Eloquent ORM.