mardi 7 juin 2022

Call to a member function comments() on null when use foreign key

This is error Call to a member function comments() on null, in model give a relation still show this error Article model

function user() {
return $this->belongsTo(User::class, 'id');
}
public function comments()
{
    return $this->hasMany(Comment::class, 'id');
}

Comment Model

 public function user()
{
    return $this->belongsTo(User::class);
}
public function article()
{
    return $this->belongsTo('App\Article');
}

This is contoller

  public function store(Request $request)
{
    //dd($request->all());
      Auth::user();   
    $comment = new Comment;
    $comment -> user_id=Auth::user()->id;
    $comment-> comment = $request->get('comment');
   $article = Article::find($request->article_id);

    $article->comments()->save($comment);
     return redirect()->back()->with('success', 'your comment,successfully save');   

}

This is blade file

<form method="post" action="">
                    @csrf
                    <div class="form-group">
                        <textarea class="form-control" name="comment"></textarea>
                        <input type="hidden" name="article_id"/>
                    </div>
                    <div class="form-group">
                        <input type="submit" class="btn btn-success" value="Add Comment" />
                    </div>
                </form>


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/czhIyN0
via IFTTT

Aucun commentaire:

Enregistrer un commentaire