2
votes

Hello I've two tables :

products :

 public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
            $table->string('title');
            ...
            $table->boolean('slider_mode')->default(false);
        });
    }

and slider :

public function up()
    {
        Schema::create('slider', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
            ...
            $table->integer('products_id')->unsigned()->index();
            $table->foreign('products_id')->references('id')->on('products')->onDelete('cascade');
        });

Problem is when I'm creating products table with slider, product's id is not referencing in products_id

Here is my controller ( store function) :

...
 if($x1['slider_mode'] == 1){      # x1 is $request->all();
            Slider::create($x1);
        }
        Product::create($x1);


        return redirect('admin/products');

should products_id is not be completed automatically with product's id when I create both ?

but I'm getting error:

General error: 1364 Field 'products_id' doesn't have a default value

2
why don't simply make product_id nullable , if you're not storing it will creating slider - kunal rajput

2 Answers

3
votes

If you set up relations inside your models, You can do that like this:

$product = Product::create($x);
$product->sliders()->create($x);

A newly created slider will automatically have a product_id of product.

You can read more here I think that's it what you need.

-1
votes

product_id is auto-increment but for products table not for the slider table.

If you want to insert into the slider table without product_id, you must update the products table migration and set the value to be nullable:

$table->integer('products_id')->unsigned()->index()->nullable();

Or if you want product_id also you should set the product_id.