Created
July 11, 2019 08:29
-
-
Save andresayej/d265986c38255b3bb4a418fe33bab32b to your computer and use it in GitHub Desktop.
Trait to save many statuses using the spatie/laravel-model-status package
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits; | |
use Illuminate\Support\Facades\DB; | |
use Spatie\ModelStatus\Exceptions\InvalidStatus; | |
trait CanSaveManyStatuses | |
{ | |
/** | |
* @param string $statusName | |
* @param array $ids | |
* @param string|null $statusReason | |
* @param int|null $chunkNumber | |
* @throws InvalidStatus | |
*/ | |
public static function saveManyStatuses( | |
string $statusName, | |
array $ids, | |
?string $statusReason = null, | |
int $chunkNumber = null | |
) { | |
$instance = new static; | |
$chunkNumber = $chunkNumber ?: 1000; | |
if (! $instance->isValidStatus($statusName)) { | |
throw InvalidStatus::create($statusName); | |
} | |
$instance->chunk($chunkNumber, function ($models) use ($instance, $statusName, $statusReason, $ids) { | |
$list=[]; | |
foreach ($models as $model) { | |
if (in_array($model->id, $ids)) { | |
$data = [ | |
'name' => $statusName, | |
'reason' => $statusReason, | |
'model_type' => $instance->getStatusModelType(), | |
$instance->getModelKeyColumnName() => $model->id, | |
'created_at' => now(), | |
'updated_at' => now(), | |
]; | |
array_push($list, $data); | |
} | |
} | |
DB::table($instance->getStatusTableName())->insert($list); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment