2017-09-02 23 views
1

上のメンバ関数同期()の呼び出し - nullの上メンバ関数同期()を呼び出します。 Debugerショーマイル、それがコードLaravel、私laravelプロジェクトで、私はFatalThrowableErrorを持ってヌル

Post::findOrFail($post_id)->tags()->sync([1, 2, 3], false); 

完全な方法のこの行で、この行は次のようになります。

public function store(Request $request) 
{ 
     // validate a post data 
    $this->validate($request, [ 
      'title' => 'required|min:3|max:240', 
      'body' => 'required|min:50', 
      'category' => 'required|integer', 
     ]); 

    // store post in the database 
    $post_id = Post::Create([ 
     'title' => $request->title, 
     'body' => $request->body, 
    ])->id; 

    Post::findOrFail($post_id)->tags()->sync([1, 2, 3], false); 

    // rediect to posts.show pages 
    return Redirect::route('posts.show', $post_id); 
} 

class Post extends Model 
{ 
    protected $fillable = [ ... ]; 

    public function category() {...} 

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

そして、私のTagモデルの外観のような私のPostモデルはそのルックスlike

class Tag extends Model 
{ 
    protected $fillable = [ ... ]; 

    public function posts() 
    { 
     return $this->belongsToMany('App\Post', 'post_tag', 'tag_id', 'post_id'); 
    } 
} 

あなたのアンサーに感謝します!

+0

あなた 'タグ()'メソッドは 'return'の文が欠落しています。 'ますreturn $ this-> belongsToMany( 'アプリケーション\タグ'、 'post_tag'、 'post_idの'、 'TAG_ID'); ' – bradforbes

答えて

0

はあなたtags()方法の結果はnullであることを意味nullオブジェクト、上sync()を呼んでいるこの

// store post in the database 
$post = new Post([ 
    'title' => $request->title, 
    'body' => $request->body, 
]); 

$post->save(); 

$post->tags()->sync([1, 2, 3], false); 
+0

あなたのアンサーに感謝しますが、これは私の問題を解決しません。私はこの同じエラーがあります。疲れた後:
'$ post = new Post;
$ post-> title = $ request-> title;
$ post-> body = $ request-> body;
$ post-> save();
$ post-> tags() - > sync([1、2、3]、false); '

+0

投稿テーブルに新しい投稿を挿入できますか?なぜ$ request-> tagsの代わりに[1,2,3]を使用していますか? –

+0

はい、私はこのテーブルを新しい投稿を作成するのが正しいです。私が使用して、[1、2、3]これは単にテストアレイ、致命的なエラーの後であるため、 –

0

エラー状態を試してみてください。

tags()メソッドを見ると、returnの関係を忘れていることがわかります。したがって、nullが返されます。 returnキーワードを追加してください。

public function tags() 
{ 
    return $this->belongsToMany('App\Tag', 'post_tag', 'post_id', 'tag_id'); 
} 
関連する問題