Search code examples
phplaraveleloquentmany-to-manylaravel-5.6

builder::sync does not exist error with many-to-many in Laravel


Similar issue to this issue here.

And I'm getting the following:

Method Illuminate\Database\Query\Builder::sync does not exist.

But my code already has the given solution...

Tag Model:

    namespace App;

    use Illuminate\Database\Eloquent\Model;

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

Post Model:

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Post extends Model
    {
      public function user(){
        return $this->belongsTo('App\User');
      }

      public function category(){
        return $this->belongsTo('App\Category');
      }

      public function tags(){
        return $this->belongsTo('App\Tag', 'post_tag');
      }
    }

Post Controller

    <?php

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use Session;
    use Carbon\Carbon;

    use App\Category;
    use App\Post;
    use App\Tag;
    use App\User;


    class PostController extends Controller
    {
      public function __construct() { 
        $this->middleware('auth');
      }
...
      public function store(Request $request)
      {

        // Validate the data
        $this->validate($request, [
          'title'       => 'required|max:255',
          'category' => 'required|integer',
          'body'        => 'required'
        ]);

        $post = new Post;
        $post->title = $request->input('title');
        $post->body = $request->input('body');
        $post->slug = uniqid();
        $post->category_id = $request->category;
        $post->user_id = auth()->user()->id;
        $post->save();

        $post->slug = str_slug($request->input('title').' '.$post->id, '-');
        $post->save();

        $post->tags()->sync($request->tags, false);


        Session::flash('success', 'The blog post was successfully saved!');

        return redirect()->route('posts.show', $post->id);
      }

A dd($request->tags) returns

array:2 [▼
   0 => "1"
   1 => "2"
 ]

Which are the correct values form the form input.

If I remove the line $post->tags()->sync($request->tags, false); it writes correctly to the DB, and if I don't, but run it anyway, it's saving the to the posts table correctly, but not the relevant values to the pivot table.


Solution

  • Change this:

    public function tags(){
        return $this->belongsTo('App\Tag', 'post_tag');
    }
    

    To this:

    public function tags(){
        return $this->belongsToMany('App\Tag', 'post_tag');
    }