0
votes

I have 3 tables:

stations (id,station_name) 
products (id,product_name)
product_station (station_id,product_id)

Station Model

protected $fillable = ['station_name'];
public function products(){
        return $this->belongsToMany(Product::class);
    }

Product Model

 protected $fillable = ['product_name'];

public function stations(){
    return $this->belongsToMany(Station::class);
}

I already have inserted stations and products and i want to insert station with it's own product using into Pivot table

AdminProductStationcontroller

public function create()
    {
        $station = Station::pluck('station_name','id')->all();

        $products = Product::pluck('product_name','id')->all();

        return view('admin.product_stations.create',compact('station','products'));
    }

I think there is error in store function below

    public function store(Request $request)
    {

        $station = new Station();

        $product = new Product();

        $station->save();

        $station->products()->attach($product);

        return redirect('/admin/product_stations');
     }

So i have got this error

(2/2) QueryException SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'product_id' cannot be null (SQL: insert into product_station (product_id, station_id) values (, 25))

4

4 Answers

2
votes

attach() expects a single or an array of ids of the related Model implying that the Model should have been created beforehand.

What you're looking for is the save(Model) method.

$station->products()->save($product);

More on the above in the docs: https://laravel.com/docs/5.8/eloquent-relationships#updating-many-to-many-relationships

1
votes

You should firstly save

$station = new Station();
$station->save();

$product = new Product();
$product->save();

then https://laravel.com/docs/6.x/eloquent-relationships#updating-many-to-many-relationships

$station->products()->attach($product->id);

OR

You can try to save like so

$station->products()->save($product);
1
votes
// Post Model
public function categories()
    {
        return $this->belongsToMany('App\Category')->withTimestamps();
    }
    public function tags()
    {
        return $this->belongsToMany('App\Tag')->withTimestamps();
    }

public function store(Request $request)
    {
        $this->validate($request,[
            'title' =>'required',
            'image' => 'mimes:jpeg,jpg,bmp,png',
            'categories' => 'required',
            'tags' => 'required',
            'body' => 'required',
            'live_demo' =>'required'
        ]);

          $image = $request->file('image');
        $slug = str_slug($request->title);
        if (isset($image))
        {
            $currentDate = Carbon::now()->toDateString();
            $imagename = $slug.'-'.$currentDate.'-'. uniqid() .'.'. $image->getClientOriginalExtension();
            $image_resize = Image::make($image->getRealPath());   
            $image_resize->resize(1600,1066);
            if (!file_exists('storage/uploads/post'))
            {
                mkdir('storage/uploads/post',0777,true);
            }
            //$image->move('storage/uploads/post',$imagename);
            $image_resize->save('storage/uploads/post/'.$imagename);
        }else{
            $imagename = "default.png";
        }

         $post = new Post();
        $post->user_id = Auth::id();
        $post->title = $request->title;
        $post->slug = str_slug($request->title);
        $post->image = $imagename;
        $post->body = $request->body;
        $post->price = $request->price;
        $post->live_demo = $request->live_demo;
        if(isset($request->status))
            {
                $post->status =true;
            }else
            {
                $post->status = false;
            }
        $post->is_approved = true;
        $post->save();
        $post->categories()->attach($request->categories);
        $post->tags()->attach($request->tags);

        Toastr::success('Post Successfully Save:)','Success');
        return redirect()->route('admin.post.index');
    }

// Pivot table create category_post column create   category_id, post_id.
// Pivot table create post_tag, and column create post_id, and tag_id
0
votes
  $station->products()->sync($request->products , false);