45 lines
1.2 KiB
PHP
45 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Lib\Helpers\ToolboxHelper;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Str;
|
|
|
|
class Recipe extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
/**
|
|
* Perform any actions required after the model boots.
|
|
*
|
|
* @return void
|
|
*/
|
|
protected static function booted()
|
|
{
|
|
static::creating(function (self $model) {
|
|
static::assertTitleIsUnique($model->title);
|
|
});
|
|
static::updating(function (self $model) {
|
|
static::assertTitleIsUnique($model->title, $model->id);
|
|
});
|
|
}
|
|
|
|
// * METHODS
|
|
|
|
/**
|
|
* Asserts using validation that the title is unique
|
|
*
|
|
* @param mixed $title
|
|
* @param integer|null $id
|
|
* @return void
|
|
* @throws \Illuminate\Validation\ValidationException If an actu title already exists.
|
|
*/
|
|
private static function assertTitleIsUnique($title, ?int $id = null)
|
|
{
|
|
$table = (new self())->getTable();
|
|
ToolboxHelper::assertFieldIsUnique($table, 'title', $title, $id);
|
|
ToolboxHelper::assertFieldIsUnique($table, 'slug', Str::slug($title), $id);
|
|
}
|
|
}
|