简体   繁体   中英

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="{{ 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>

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM