50 lines
1.5 KiB
PHP
50 lines
1.5 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Traits\Controllers;
|
|
|
|
use App\Interfaces\ModelWithStatus;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Http\RedirectResponse;
|
|
use Illuminate\Support\Collection;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Str;
|
|
|
|
/** @mixin \Illuminate\Routing\Controller */
|
|
trait TogglesModelStatus
|
|
{
|
|
/**
|
|
* Toggles model status
|
|
*/
|
|
public function toggleStatus(): RedirectResponse
|
|
{
|
|
/** @var Model|null $model */
|
|
$model = Collection::make(request()->route()?->parameters())
|
|
->first(fn ($param) => $param instanceof Model);
|
|
|
|
if ($model === null) {
|
|
throw new \InvalidArgumentException('No model found in route parameters');
|
|
}
|
|
|
|
if (! $model instanceof ModelWithStatus || ! $model instanceof Model) {
|
|
throw new \InvalidArgumentException('Model must implement ModelWithStatus and extend Model');
|
|
}
|
|
|
|
$this->authorize('toggleStatus', $model);
|
|
|
|
return DB::transaction(function () use ($model) {
|
|
$model->toggleStatus();
|
|
|
|
if ($model->saveOrFail()) {
|
|
return back()->with('success', trans('crud.messages.has_been_updated', [
|
|
'model' => Str::ucfirst(trans_choice('models.classes.' . $model->getTable(), 1)),
|
|
]));
|
|
}
|
|
|
|
return back()->with('error', trans('crud.messages.cannot_be_updated', [
|
|
'model' => Str::ucfirst(trans_choice('models.classes.' . $model->getTable(), 1)),
|
|
]));
|
|
});
|
|
}
|
|
}
|