Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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 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>

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading