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

Time:06-07

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="{{ route('comment.store') }}">
                    @csrf
                    <div >
                        <textarea  name="comment"></textarea>
                        <input type="hidden" name="article_id"/>
                    </div>
                    <div >
                        <input type="submit"  value="Add Comment" />
                    </div>
                </form>

CodePudding user response:

You need to set a value for the hidden field.

<input type="hidden" name="article_id" value="{{ $article->id }}"/>

Secondly for easier debugging these errors, using findOrFail() will ensure your app blows up, with a proper error message. Instead of just returning null.

$article = Article::findOrFail($request->article_id);

EDIT

You are also mixing two saving approaches together, either you associate the article to the comment or create a new comment. This is the approach i like to use.

$comment = new Comment;
$comment->user_id = Auth::user()->id;
$comment->comment = $request->get('comment');

$article = Article::find($request->article_id);
$comment->article()->associate($article);
$comment->save();
  • Related