0
votes

I'm getting this error while up entering data to my table

class EntryController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */


    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */

    public function entry(Request $request){

        $category = category::create(['cat_name' => $request->input('cat_name')]);

         $product= product::create([
            'Product_name'=>$request->input('Product_name'),
            'Produc_quantity'=>$request->input('Produc_quantity'),
            'Product_Desc' =>$request->input('Product_Desc'), 
            'cat_id'=>$category->cat_id]);


class category extends Model
{
    protected $fillable = array('cat_description','cat_name');


    public function product()
    {
        return $this->hasMany(product::class);


    }
//
}

these are my models

class product extends Model
{
    protected   $fillable = array('Product_name','Product_Desc',
                                  'Produc_quantity','sale_price',
                                  'cost_price');
    public function category()
    {
        return $this->belongsTo(category::class);


    }
        //
}

this is product table

this is category table

I've removed the cat_id from $fillables in product model and this is giving this error and I'm not understanding this I've check many forums and questions but I didn't find an answer this is product table

 Schema::create('products', function (Blueprint $table) {
        $table->increments('product_id');
        $table->string('Product_name');
        $table->string('Product_Desc');
        $table->integer('sale_price');
        $table->integer('cost_price');
        $table->integer('Produc_quantity');
       $table->integer('cat_id')->unsigned();
        $table->foreign('cat_id')->references('cat_id')->on('categories');
        $table->timestamps();

this is category table

  Schema::create('categories', function (Blueprint $table) {
        $table->increments('cat_id');
        $table->string('cat_name');
        $table->string('cat_description');


        $table->timestamps();
2
It might be a typo but your first class is not erminate } before you start your second classRiggsFolly
Is cat_id an auto-increment field in your database?olibiaz
yes it is auto incrementUzair
Take the cat_id off on your $fillable since it's auto-increment.Ronald
I remove cat_id from $fillables now I'm getting this SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row:Uzair

2 Answers

0
votes

Are you sure that the category has been created successfully?
If so, maybe you need to add cat_id to your $fillable.
Also when using custom id like cat_id you need to add

public $primaryKey = 'yourkey' 
0
votes

I solve this problem actually there is a problem in my product model $fillables I add cat_id in my category model $fillables which solve this problem thank you for your help