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)
CodePudding user response:
I think you should not add the category_slug
to your products table
you already have all the information you need about the product's category when you added the category_id
to the products
table
to get the category_slug
from the product
you can do something like this
Product::with('category')->find(1)->category->slug
CodePudding user response:
The problem lies here :
$code->category_slug=$request->category_slug;
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:
$code->category_slug= \Str::slug($request->name . '-' .$request->category_id);
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:
$code->category_slug=$code->category->category_slug;
You might need to use $code->save() instead of update()
CodePudding user response:
Change your migration.
public function up()
{
Schema::table('products', function (Blueprint $table) {
$table->string('category_slug')->nullable()->change();
});
}
It seems that you are not sending any value to the category_slug
column while updating the record. The column must have a nullable
constraint.