Laravel 7 : attach pivot to table with multiple values

  laravel, pivot

I’m creating a pivot tables for 3 columns

my pivot table name is : category_post_pad

category_id|  post_id | pad_id
-----------|----------|--------
 1         |        1 |      3
 1         |        4 |      1
 2         |        2 |      1

Each post sent by the user includes a category and an pad

Post Model

public function categories()
{ 
 return $this->belongsToMany(Category::class,'category_post_pad','post_id','category_id');
}

public function pads()
{
return $this->belongsToMany(Pad::class,'category_post_pad','post_id','pad_id');
}

category model:

public function posts()
{
    return $this->belongsToMany(Post::class,'category_post_pad','category_id','post_id');

}

pad model:

public function posts()
{
    return $this->belongsToMany(Post::class,'category_post_pad','pad_id','post_id');

}

PostsController

    public function store(Request $request)
{
    $data = $request->all();
    $post = Post::create($data);
    if ($post && $post instanceof Post) {
        $category = $request->input('categories');
        $pad = $request->input('pads');
        $post->categories()->attach([$category],[$pad]);
        return redirect()->back();
    }

}

but show me this error

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘0’ in ‘field list’ (SQL: insert into category_post_pad (category_id, post_id, 0) values (3, 104, 2))

how to fixit?

Source: Laravel StackOverflow

Leave a Reply