I have a problem when I try to modify existing data in the database. It is a product category that has a unique slug. When I create a new category I check if there is a slug
in the database. When I want to change the existing category, I get an error that the slug
is already taken.
I found some examples on StackOveflow but nothing can solve my problem.
Structure
category table
category_id, parent_id, status, created_at, ...
--------------------------------------------------
category_details
category_id, name, slug, description, ....
--------------------------------------------------
Models
class Category extends Model
{
use HasFactory;
protected $table = "category";
protected $fillable = [
'parent_id',
'image',
'status',
'show_in_menu',
'sort_order'
];
/**
* Category details table
*/
public function details()
{
return $this->hasOne(CategoryDetails::class, 'category_id', 'id');
}
}
class CategoryDetails extends Model
{
use HasFactory;
protected $primaryKey = 'category_id';
protected $fillable = [
'category_id',
'name',
'slug',
'description',
'description_below',
'meta_title',
'meta_description'
];
}
Form Request Class
public function rules(): array
{
if($this->isMethod('post')) {
return [
'name' => 'required',
'slug' => 'required|unique:category_details',
'meta_title' => 'required|max:60',
'meta_description' => 'max:160',
'status' => 'accepted'
];
}
if($this->isMethod('patch')) {
return [
'name' => 'required',
'slug' =>'required|unique:category_details,slug,'.$this->category_id,
'meta_title' => 'required|max:60',
'meta_description' => 'max:160',
];
}
}
Controller
public function update(CategoryRequest $request, int $id)
{
$category = Category::find($id)->first();
$category->update([
'parent_id' => $request->input('parent_id'),
'image' => '',
'status' => $request->input('status') == 'on' ? 1 : 0,
'sort_order' => $request->input('sort_order')
]);
$category->details->update([
'category_id' => $id,
'name' => $request->input('name'),
'slug' => $request->input('slug'),
'description' => $request->input('description'),
'meta_title' => $request->input('meta_title'),
'meta_description' => $request->input('meta_description')
]);
return redirect()
->route('categories.edit', $category->id)
->with('success', "Category {$category->details->name} successfully updated");
}
Error Message
I received an error during the update event.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause'
select
count(*) as aggregate
from `category_details`
where `slug` = dekubitus2
and `id` <>