Dahdoul
3 years ago
281
2
Laravel

Save multiple data to pivot table

Posted 3 years ago by Dahdoul

Hello,

I have post where belongs to many categories, I'm trying to save multiple categories for one post to pivot table (category_post), but whenever I submit the post I get the following error.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id' cannot be null (SQL: insert into `category_post` (`category_id`, `post_id`) values (1, ))

Post model

class Post extends Model
{
public function categories(){
        return $this->belongsToMany('App\Category');
    }
}

Category model


class Category extends Model
{
  public function posts(){
        return $this->belongsToMany('App\Post');
    }
}

Form view

{!! Form::open(['action' => array('[email protected]'),'method'=>'post']) !!}
                        {!! Form::text('title') !!}
                        {!! Form::textarea('body') !!}
                        {!! Form::select('categories[]', $categories, null, ['multiple' => true]) !!}
                        {!! Form::select('active', ['0' => 'Not Active', '1' => 'Active'], '0')!!}
                        {!! Form::submit('submit') !!}
{!! Form::close() !!}

Migrations

Schema::create('category_post', function (Blueprint $table) {
            $table->integer('post_id');
            $table->integer('category_id');
        });

 Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
        });

Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->integer('user_id')->unsigned()->index();
            $table->integer('updated_by')->nullable()->index();
            $table->boolean('active')->default(0);
            $table->timestamps();
        });

Post Controller

 public function store(Request $request)
    {
        //
        $input = $request->all();
        $post = new Post();
        if (Auth::user()) {
            $input['user_id'] = Auth::user()->id;
        }
        $post->create($input);
        $post->categories()->sync($input['categories'],false);
    // tried this       $post->categories()->sync($input['categories'],[$post->id]);
        return redirect()->back();
    }

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