SQLSTATE[23000]: Integrity constraint violation: 1048 Column ‘category_slug’ cannot be null (SQL: update
products
setcategory_slug
= ?,products
.updated_at
= 2022-12-23 12:06:26 whereid
= 1)
How I get product category_slug colmun from category slug table.
Categories Table:
|id|name|slug |
|4 |Cat4|cat-4|
|5 |Cat5|cat-5|
|6 |Cat6|cat-6|
Products Table
|id|name|category_id|category_slug|
|1 |USDT|4 |cat-4 |
|2 |BTCH|5 |cat-5 |
|3 |EURT|6 |cat-6 |
Product Controller (Update Method)
public function update(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:190',
'price' => 'required',
'category_id' => 'required',
])->validate();
$code=Product::find($request->id);
$code->name=$request->name;
$code->category_id=$request->category_id;
$code->category_slug=$request->category_slug;
$code->update();
return redirect()->back()->with('success',__('Product has been updated'));
}
`
Product Model
`
class Product extends Model
{
use HasFactory;
public function category()
{
return $this->hasOne(Category::class,'id','category_id');
}
`
I GET THIS ERROR
SQLSTATE[23000]: Integrity constraint violation: 1048 Column ‘category_slug’ cannot be null (SQL: update
products
setcategory_slug
= ?,products
.updated_at
= 2022-12-23 12:06:26 whereid
= 1)
3
Answers
Change your migration.
It seems that you are not sending any value to the
category_slug
column while updating the record. The column must have anullable
constraint.The problem lies here :
It seems that $request->category_slug is null/undefined. If you are sure sending it from the frontend via an input make sure it has the right name attribute name="category_slug"
If however, you don’t send it from frontend you should use slug helper to generate it from a string you chose, example:
This will generate a slug from the name and id combined.
EDIT: If you want to get the current Product category slug you can use it like so:
You might need to use $code->save() instead of update()
I think you should not add the
category_slug
to your products tableyou already have all the information you need about the product’s category when you added the
category_id
to theproducts
tableto get the
category_slug
from the productyou can do something like this