KACKbIP
4 months ago
464
13
Laravel

Hi, How to save one to one relationship data?

Posted 4 months ago by KACKbIP

I am trying to save 6 picture which are related to products

    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->text('description');
            $table->string('image')->nullable();
            $table->string('price')->nullable();
            $table->string('discount')->nullable();
            $table->string('category_id')->nullable();
            $table->string('label')->nullable();
            $table->string('option_id')->nullable();
            $table->text('short_desc')->nullable();
            $table->text('long_desc')->nullable();
            $table->timestamps();
        });
    }

my product table

 public function up()
    {
        Schema::create('pictures', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('picture1')->nullable();
            $table->string('picture2')->nullable();
            $table->string('picture3')->nullable();
            $table->string('picture4')->nullable();
            $table->string('picture5')->nullable();
            $table->string('picture6')->nullable();
            $table->string('product_id')->nullable();
            $table->timestamps();
        });
    }

My pictures table

 public function store(Request $request)
    {
        $product = new Product();

        $product->name = $request->name;
        $product->category_id = $request->category_id;
        $product->description = $request->description;
        $product->price = str_replace(' ', '', $request->price);
        $product->discount = str_replace(' ', '', $request->discount);
        $product->long_desc = $request->long;
        $product->short_desc = $request->short;
        $product->label = $request->options;
        $product->title = $request->title;
        $product->desc = $request->desc;

        $fileName = null;
        if (request()->hasFile('image')) {
            $file = request()->file('image');
            $fileName = rand() . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('images'), $fileName);
        }


        $product->image = $fileName;

        $product->save();

        return redirect('admin/product')->with('success', ' добавили товар.');

    }

My controller

class Product extends Model
{

    public function category()
    {
        return $this->hasOne('App\Category');
    }

    public function option()
    {
        return $this->hasOne('App\Option');
    }

    public function picture()
    {
        return $this->hasOne('App\Picture');
    }

}

My Product model

Please sign in or create an account to participate in this conversation.