ldc-nature-and-respect/app/Traits/Controllers/UpdateModelStatus.php

68 lines
1.9 KiB
PHP
Raw Permalink Normal View History

2023-03-16 15:08:37 +01:00
<?php
namespace App\Traits\Controllers;
2025-02-26 13:02:02 +01:00
use App\Interfaces\Models\Publishable;
2023-03-16 15:08:37 +01:00
use Illuminate\Database\Eloquent\Model;
2025-02-26 13:02:02 +01:00
use App\Traits\Models\IsPublishable;
2023-03-16 15:08:37 +01:00
/**
* This trait works with Route::bind in App service provider
* to resolve the model and the DB row
* It does not work with binder Service
*/
trait UpdateModelStatus
{
/**
2025-02-26 13:02:02 +01:00
* Change model published boolean
2023-03-16 15:08:37 +01:00
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return \Illuminate\Http\RedirectResponse
*/
public function changePublished(Model $model)
{
2024-01-29 16:02:03 +01:00
$model->update(['status' => !$model->getOriginal('status')]);
2023-03-23 09:08:28 +01:00
return redirect()->back()->with('success', __('The status has been changed'));
2023-03-16 15:08:37 +01:00
}
2025-02-26 13:02:02 +01:00
/**
* Change model publication date + boolean
*
* @param Model $model
* @return \Illuminate\Http\RedirectResponse
* @throws \InvalidArgumentException Model must use IsPublishable trait.
2025-02-26 13:02:02 +01:00
*/
public function updatePublicationDate(Model $model)
{
if (!$this->isPublishable($model)) {
throw new \InvalidArgumentException('Model must use IsPublishable trait');
}
/** @var Publishable&Model $model */
if ($model->getStatus()) {
$model->setUnpublishAt(now());
$model->setStatus(false);
} else {
$model->setPublishAt(now());
$model->setUnpublishAt(null);
$model->setStatus(true);
}
$model->saveOrFail();
return redirect()->back()->with('success', __('The status has been changed'));
}
/**
* Check if a Model implements Publishable interface.
*
* @param \Illuminate\Database\Eloquent\Model $model
*
* @return boolean
*/
protected function isPublishable(Model $model): bool
{
return $model instanceof Publishable &&
in_array(IsPublishable::class, class_uses_recursive($model));
}
2023-03-16 15:08:37 +01:00
}