Support the ongoing development of →
Database Eloquent Blade
Last updated 4 months ago.

relationships still stump me sometimes, but if I am correct, you should call


//instead of

Your understanding on foreign key and local key are wrong. Your relations are incorrect as well.

So, here's the setup I assume:

forums: id, last_comment_id, ...
topics: id, ...
comments: id, topic_id, ...

then id are always local keys in the context of any relation. That said, here are your relations:

// Forum
public function lastcomment()
  return $this->belongsTo('Comment', 'last_comment_id');

// Comment
public function forum()
  return $this->hasOne('Forum', 'last_comment_id');

However having this setup your Forum depends on the comments, which is not the way to go. Instead create proper relations:

// Forum
public function comments()
  return $this->hasManyThrough('Comment', 'Topic');

no relation from Comment to the Forum, since you will call $comment->topic->forum if you need.

Also, for the latest comment for given forum, use this:

and you will be able to do what you wanted:

if (count($forum->lastcomment)) {  // chech if there's any comment first
Last updated 7 years ago.

Sign in to participate in this thread!

Full Stack Europe

Your banner here too?

Maxime-BHA maxime-bha Joined 25 Jun 2014


We'd like to thank these amazing companies for supporting us

Your logo here?

The Laravel portal for problem solving, knowledge sharing and community building.

© 2022 - All rights reserved.