why are you referencing id as the key on the Comments author relationship? this should be author_id ?
You may find it easier to spot the issue if you bump the ids on the tables so that they are not all 1 and 2 in all models
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Good afternoon,
I have tried my very hardest to fix this problem reading through all the threads I could find on this issue but I still have had no luck in fixing my problem. If anyone could help me I would really appreciate it!
Here is a picture of the Database Schema.
$table->integer('entry_id')->unsigned();
$table->foreign('entry_id')->references('id')->on('entries')->onDelete('cascade');
$table->integer('author_id')->unsigned();
$table->foreign('author_id')->references('id')->on('authors');
public function comments() {
return $this->hasMany('App\Models\Comment');
}
public function comments() {
return $this->hasMany('App\Models\Comment');
}
public function entry() {
return $this->belongsTo('App\Models\Entry');
}
public function author() {
return $this->belongsTo('App\Models\Author', 'id');
}
$entries = Entry::with('comments.author')->get();
At this point everything is working correctly so the above $entries contains the expected Collection made up of:
*All entires, nested within each:
**all associated comments, and nested within that
***the associated author for each comment.
1/2 ErrorException in 991fecee1bbd0eb1ec5070d2f47d9c641ca4a735.php line 24:
Trying to get property of non-object
I only get the above error when multiple author_id are the same. Therefore I know that there is no problem in the way I am accessing the collections data in the view.
| id | author_id | text |
|---- |----------- |------- |
| 1 | 1 | blah1 |
| | | |
select * from `entries`
select * from `comments` where `comments`.`entry_id` in ('1')
select * from `authors` where `authors`.`id` in ('1')
#relations: array:1 [▼
"author" => Author {
//all correct data displays here
| id | author_id | text |
|---- |----------- |------- |
| 1 | 1 | blah1 |
| 2 | 1 | blah2 |
| | | |
select * from `entries`
select * from `comments` where `comments`.`entry_id` in ('1', '2')
select * from `authors` where `authors`.`id` in ('1', '2')
#relations: array:1 [▼
"author" => null
]
I believe the issue is that the 3rd query contains: "in ('1', '2')" where 2 doesn't exist.
Does anyone have any thoughts on how to fix this? I really would like to be able to successfully utilise Laravel's built in eloquent nested relationship system. But if this is not doable do I need to write me own custom query? Any input would be wonderful! I'm really stuck on this.
Thanks for your time and help.
why are you referencing id as the key on the Comments author relationship? this should be author_id ?
You may find it easier to spot the issue if you bump the ids on the tables so that they are not all 1 and 2 in all models
Please or to participate in this conversation.