How can I code a method in model that I use it for multiple records like delete or update?
User::whereIn('id', [1, 2, 3])->delete();
My method is like this:
public function remove()
{
$this->update([
'expired_at' => now()->addYear()
]);
}
But above method can update one record and I can't use :
User::whereIn('id', [1, 2, 3])->remove();
I try this
public function remove()
{
$this->update([
'expired_at' => now()->addYear()
]);
}
CodePudding user response:
This is how you can do it based on the destroy()
function in laravel-9 model:
User Model (Add): (change line 31 accordingly)
/**
* Update the models for the given IDs.
*
* @param \Illuminate\Support\Collection|array|int|string $ids
* @return int
*/
public static function remove($ids)
{
if ($ids instanceof EloquentCollection) {
$ids = $ids->modelKeys();
}
if ($ids instanceof BaseCollection) {
$ids = $ids->all();
}
$ids = is_array($ids) ? $ids : func_get_args();
if (count($ids) === 0) {
return 0;
}
// We will actually pull the models from the database table and call update on
// each of them individually so that their events get fired properly with a
// correct set of attributes in case the developers wants to check these.
$key = ($instance = new static)->getKeyName();
$count = 0;
foreach ($instance->whereIn($key, $ids)->get() as $model) {
//Do your update query here
if ($model->update(['expired_at' => now()])) {
$count ;
}
}
return $count;
}
Controller call:
//List of model IDs
User::remove([2, 3, 4, 5, 6]);
Alternatively if you just want to update directly without creating extra logics, you can always just call like this:
User::whereIn('id', [6, 7])->update(['expired_at' => now()]);
But if you want to handle complex operations like comparing dates, changing records and other things, then modify the foreach loop according to your needs.
CodePudding user response:
You can do like this
public function remove($ids)
{
User::whereIn('id', $ids)->update([
'expired_at' => now()->addYear()
]);
}
And Id's array
$ids = [1, 2, 3];
User::remove($ids);