How to store data on a pivot table with eloquent?

  eloquent, laravel, pivot

I am trying to store a "project" with its respective categories. the categories are already defined in the category table.
in category_project pivot table I have category_id and project_id.

I have been able to get the category_id, but not the Project_id – When I submit the create form

Laravel throws me an error saying that the project_id field cannot be null. but I don’t know how to get that project_id together with the category_id

:::CONTROLLER - ProjectController

   

 $project = new Project();
        $project->title = request('title');
        $project->client = request('client');
        $project->description = request('description');
        $project->year = request('year');
        $project->categories()->sync($request->categories);
        $project->tools()->sync($request->tools);

        $project->save();
    ```

:::MODEL – Project

class project extends Model
{

protected $fillable = [
    'title' ,
    'client' ,
    'description',
    'year',
 
];


public function categories(){
    return $this->belongsToMany(Category::class);
}
public function tools(){
    return $this->belongsToMany(Tool::class);
}
public function images(){
    return $this->belongsToMany(Image::class);
}

}




:::MODEL – Category

class category extends Model

{
protected $fillable = [
‘name’ ,

];
public function projects(){
    return $this->belongsToMany(Project::class);
}

}


:::VIEW – (piece) CreateProject.blade.php

<select multiple class="form-control" id="exampleFormControlSelect2" name="categories[]">
@foreach($categories as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
@endforeach
Sql ERROR

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


Source: Laravel

Leave a Reply