Laravel Method sync does not exist

2019-08-26 22:40发布

Post Model

<?php

namespace App\Model\User;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
   public function tags(){
     return $this->belongsToMany('App\Model\User\Tag','post__tags', 'post_id', 'tag_id');
  }

  public function categories() {
     return $this->belongsToMany('App\Model\User\Category','category__posts','post_id', 'category_id');
  }
}

Category Model

<?php

namespace App\Model\User;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
   public function posts(){
      return $this->belongsToMany('App\Model\User\Category','category__posts', 'post_id', 'category_id');
   }

}

Tag Model

<?php

namespace App\Model\User;

use Illuminate\Database\Eloquent\Model;

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

PostController.php

public funcion store()
{
// do validation here
   try{
      $post = new Post;
      $post->title = $request->title;
      $post->subtitle  =  $request->subtitle;
      $post->slug  =  $request->slug;
      $post->body  =  $request->body;           
      $post->status  =  1;                   
      $post->save();     // This works correct 
      $post->tags->sync($request->tags); // Not working
      $post->categories->sync($request->categories);  // Not working
   }
   catch(\Exception $e){ 
      return redirect(route('post.index'))->with('message', 'Error Adding Post into system!'.$e->getMessage()); // getting Message "Method sync does not exist. "
    }      
}

2条回答
老娘就宠你
2楼-- · 2019-08-26 22:51

Sync is a method on the builder instance, you're using it on the collection.

 // change your code like this
 $post->tags()->sync($request->tags);
 $post->categories()->sync($request->categories);
查看更多
聊天终结者
3楼-- · 2019-08-26 23:10

You need to use the following:

$post->tags()->sync($request->tags);
$post->categories()->sync($request->categories);

Don't forget the () in tags and categories

$post->categories without () is a Collection instance.

$post->categories() is a belongsToMany instance

查看更多
登录 后发表回答