99 lines
2.8 KiB
PHP
99 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Lib\Helpers\ToolboxHelper;
|
|
use Carbon\Carbon;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Validation\ValidationException;
|
|
|
|
class Slider extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
/**
|
|
* The attributes that are mass assignable.
|
|
*
|
|
* @var string[]
|
|
*/
|
|
protected $fillable = [
|
|
'label'
|
|
];
|
|
|
|
/**
|
|
* Perform any actions required after the model boots.
|
|
*
|
|
* @return void
|
|
*/
|
|
protected static function booted()
|
|
{
|
|
// * EVENT CLOSURES.
|
|
static::creating(function (self $model) {
|
|
// * ASSERTIONS
|
|
static::assertTitleIsUnique($model->label);
|
|
// * TRANSFORMATIONS
|
|
$model->slug = Str::slug($model->label);
|
|
});
|
|
static::updating(function (self $model) {
|
|
// * ASSERTIONS
|
|
static::assertTitleIsUnique($model->label, $model->id);
|
|
// * TRANSFORMATIONS
|
|
$model->slug = Str::slug($model->label);
|
|
});
|
|
static::deleting(function (self $model) {
|
|
if ($model->slides()->count()) {
|
|
throw ValidationException::withMessages([
|
|
'Impossible de supprimer le slider car des slides y sont associés'
|
|
]);
|
|
}
|
|
});
|
|
}
|
|
|
|
// * RELATIONSHIPS
|
|
|
|
/**
|
|
* hasMany slides relation
|
|
*
|
|
* @return \Illuminate\Database\Eloquent\Relations\HasMany
|
|
*/
|
|
public function slides()
|
|
{
|
|
return $this->hasMany(Slide::class, 'slider_id')->orderBy('order', 'ASC');
|
|
}
|
|
|
|
// * METHODS
|
|
|
|
/**
|
|
* Asserts using validation that the label is unique
|
|
*
|
|
* @param mixed $label
|
|
* @param integer|null $id
|
|
* @return void
|
|
* @throws \Illuminate\Validation\ValidationException If an actu title already exists.
|
|
*/
|
|
private static function assertTitleIsUnique($label, ?int $id = null)
|
|
{
|
|
$table = (new self())->getTable();
|
|
ToolboxHelper::assertFieldIsUnique($table, 'label', $label, $id);
|
|
ToolboxHelper::assertFieldIsUnique($table, 'slug', Str::slug($label), $id);
|
|
}
|
|
|
|
/**
|
|
* Getter showable_slides filtered slides relation by showable date
|
|
*
|
|
* @return \Illuminate\Database\Eloquent\Collection<\App\Models\Slide>
|
|
*/
|
|
public function getShowableSlidesAttribute()
|
|
{
|
|
$now = Carbon::now();
|
|
return $this->slides()->where(function ($q) use ($now) {
|
|
$q->whereDate('publish_at', '<=', $now)
|
|
->orWhereNull('publish_at');
|
|
})->where(function ($q) use ($now) {
|
|
$q->whereDate('unpublish_at', '>=', $now)
|
|
->orWhereNull('unpublish_at');
|
|
})->orderBy('order', 'ASC')->get();
|
|
}
|
|
}
|