ldc-le-gaulois-pro/app/Models/NewsCategory.php
Jérémy Munsch 3a0d4e9d20
PHPstan OK
2024-02-05 09:33:08 +01:00

75 lines
2.1 KiB
PHP

<?php
namespace App\Models;
use App\Lib\Helpers\ToolboxHelper;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Str;
/**
* @property integer $id Id.
* @property string $label Label.
* @property string $slug Slug of the title.
* @property-read \Illuminate\Support\Carbon $created_at Created date.
* @property-read \Illuminate\Support\Carbon $updated_at Updated date.
*
* @property-read \Illuminate\Database\Eloquent\Collection<\App\Models\News> $news
* News Belongs-To-Many relationship.
*/
class NewsCategory extends Authenticatable
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int,string>
*/
protected $fillable = [
'label',
'slug',
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
static::updating(function (self $model) {
self::assertLabelIsUnique($model->label, $model->id);
$model->slug = Str::slug($model->label);
});
}
// * METHODS
/**
* Asserts using validation that the label is unique.
*
* @param string $label
* @param integer|null $id
* @return void
* @throws \Illuminate\Validation\ValidationException If an actu label already exists.
*/
private static function assertLabelIsUnique(string $label, ?int $id = null): void
{
$table = (new self())->getTable();
ToolboxHelper::assertFieldIsUnique($table, 'label', $label, $id);
ToolboxHelper::assertFieldIsUnique($table, 'slug', Str::slug($label), $id);
}
// * RELATIONSHIPS
/**
* BelongsToMany news
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function news(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->belongsToMany(News::class);
}
}