1
votes

new-job.blade.php

<select class="js-example-basic-multiple categories  form-control" name="categories[]" style="width: 100%" multiple="multiple">
    <option value=""></option>
    @foreach($array['categories'] as $key => $category)
        <option value="{!! $category->id !!}">{!! $category->category_name !!}</option>
    @endforeach
</select>

This is the multiple select box and it is working. $array['categories'] have all the categories in my category table

And in controller

dd($request['categories']);

gives me an an array of selected category id's eg: ['1','2']

but when i try to sync it with pivot table

$job->categories()->sync($request['categories']);

I'am getting this error

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (jobs_website.category_job_post, CONSTRAINT category_job_post_category_id_foreign FOREIGN KEY (category_id) REFERENCES category (id) ON DELETE CASCADE) (SQL: insert into category_job_post (category_id, job_post_id) values (11, 1))

I don't have an id like 11 in my category table

JobPost.php

public function categories() {
    return $this->belongsToMany('App\Category', 'category_job_post', 'category_id', 'job_post_id');
}

Category.php

public function jobs() {
    return $this->belongsToMany('App\JobPost');
}
1

1 Answers

1
votes

You have to switch the column names

public function categories() {
    return $this->belongsToMany('App\Category', 'category_job_post', 'job_post_id', 'category_id');
}