调用未定义的方法Illuminate \ Database \ Query \ Builder :: tags()

时间:2018-10-29 11:08:15

标签: laravel laravel-5.4 jquery-select2

我的表单中有以下用于在博客文章中创建标签的标签字段,因为博客标签可以与一个帖子相关多个,因此我使用select2,这是我输入的字段已使用:

 {{ Form::label('tags', 'Tags:') }}
      <select name="tags[]" class="form-control select2-multi" multiple="multiple">
          @foreach($tags as $tag)
             <option value="{{ $tag->id }}">{{ $tag->name }}</option>
          @endforeach
      </select>

这是数据进行验证然后存储到数据库中的功能

public function store(Request $request)
    {

        //   --------       WORKFLOW  HERE  ------
        // validate the data from the form
        $this->validate($request,array(

                'title'       => 'required|max:255',
                'slug '       => '|min:5|alpha_dash|max:255|unique:posts,slug|',
                'category_id' => 'required|integer',
                'body'        => 'required'

        ));  // end of validation

        // sotre that data into database
        $post = new Post;
        $post->title        = $request->title;
        $post->slug         = $request->slug;
        $post->category_id  = $request->category_id;
        $post->body         = $request->body;

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

        Session::flash('success','Your Post has been Successful saved !');
        // and then redirect the user to some page
        return redirect()->route('posts.show',$post->id);


    }

尝试保存帖子时遇到以下错误

Call to undefined method Illuminate\Database\Query\Builder::tags()

标记模型

class Tag extends Model
{
    public function post(){

    return $this->belongsToMany('App\Post');
   }
}

表结构post_tag

enter image description here

1 个答案:

答案 0 :(得分:1)

在您发布的模型中添加此

public function tags()
{
    return $this->hasMany(Tag::class,'id','post_id');
}