Ad

Laravel Many To Many Relation New

- 1 answer

i am facing a problem. i am new in laravel . i created many to many relation in my application.but it's shown error. please check bellow code :

Error

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id' cannot be null (SQL: insert into `category_post` (`category_id`, `created_at`, `post_id`, `updated_at`) values (1, 2019-11-09 17:00:29, ?, 2019-11-09 17:00:29))

Post Model code :

public function  categories()
{
    return $this->belongsToMany('App\Category')->withTimestamps();
}

Category model code

public function posts()
{
    return $this->belongsToMany('App\Post')->withTimestamps();
}

PostController Code

 public function store(Request $request)
{
    $this->validate($request,[


    ]);

    $image = $request->file('image');
    $slug = str_slug($request->name);

    if(isset($image))
    {
        $imageName = $slug.'-'.time().uniqid().'.'.$image->getClientOriginalExtension();

        if(!Storage::disk('public')->exists('posts/'))
        {
            Storage::disk('public')->makeDirectory('posts/');
        }
        $postImage = Image::make($image)->resize(1600,1066)->stream();

        Storage::disk('public')->put('posts/'.$imageName,$postImage);
    }else{

        $imageName = 'default.png';
    }



    $posts = new Post();

    $posts->user_id =Auth::id();

    $posts->title = $request->title;
    $posts->slug = $slug;
    $posts->body = $request->body;
    $posts->image = $imageName;

    $posts->categories()->attach($request->categories);
    $posts->tags()->attach($request->tags);

    $posts->is_approved = true;
    if(isset($request->status))
    {
        $posts->status = true;
    }else{

        $posts->status = false;
    }



    $posts->save();

  //  $posts->tags()->attach($request->tags);
    Toastr::success('Post Is created successfully','Success');
    return redirect()->route('admin.posts.index');

}

My create.blde.php file code is okey all request goes appropriately but above error shown when i submit my post..Thank in advance

Ad

Answer

You have a belongs to many relationship between posts and categories. In order to create that relationship on your pivot table, you must have a category_id and a post_id.

This line in your code:

 $posts->categories()->attach($request->categories);

is correct, but you are trying to attach the categories to the post object before you have saved it. Thus, the unsaved post object has no id yet.

Save your post, and then attach the categories with the attach() method you have already written.

Same thing with your tags() attachment. Stick it in after you have saved the post object.

Ad
source: stackoverflow.com
Ad