Why is it not just using first() when the entry exists? Instead it will try to create a duplicated entry which causes an error
//is found
Field::where('slug', $fullNameField['slug'])->where('kind_id', $fullNameField['kind_id'])->first();
//will try to create anyways which causes an error
Field::firstOrCreate($fullNameField);
//will try to create anyways which causes an error
Field::where('slug', $fullNameField['slug'])->where('kind_id', $fullNameField['kind_id'])->firstOrCreate($fullNameField);
//migration
Schema::create('fields', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('kind_id');
$table->foreign('kind_id')->references('id')->on('kinds');
$table->string('slug')->nullable();
$table->unique(['slug', 'kind_id']);
$table->string('name');
$table->json('validations')->nullable();
$table->timestamps();
});
//model
<?php
class Field extends Model
{
protected $guarded = [];
protected $casts = [
'validations' => 'json',
];
public function kind(): BelongsTo
{
return $this->belongsTo(Kind::class);
}
public function setNameAttribute($value)
{
$this->attributes['name'] = $value;
if (!$this->slug) {
$this->slug = $value;
}
}
public function setSlugAttribute($value)
{
$this->attributes['slug'] = Str::lower(Str::slug($value));
}
}