Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

PowerRangers's avatar

Eloquent Nested Relationship Returning null. Creating inaccurate query.

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!

Background

I'm using Laravel 5.2 within the Homestead environment on Ubuntu 14.04.

Database

I have 3 tables: entries, comments, authors. All PK's are named 'id'

Here is a picture of the Database Schema.

Relevent Migration Details(comment table migration):

    $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');

Models:

Entry model:

      public function comments() {
        return $this->hasMany('App\Models\Comment');
      }

Author model:

    public function comments() {
      return $this->hasMany('App\Models\Comment');
    }

Comment model:

    public function entry() {
      return $this->belongsTo('App\Models\Entry');
    }
    public function author() {
      return $this->belongsTo('App\Models\Author', 'id');
    }

Controller: (Nested relationship query)

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

The Problem

The problem occurs when I have a multiple comments in the DB which contain the same author_id value. In this scenario, the laravel Collection gives me the expected data for the first instance(a valid nested comment collection with nested author), but any later instances which contain the same author_id have a value of null inside the relations property which results in the following error:
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.

Debugging the Queries created by eloquent:

Working query: (when all comments in the DB have a unique author_id)EG:

| 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

Problematic query: (when there is a comment in the DB which shares an author_id with another comment)EG:

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

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

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

2 likes
PowerRangers's avatar

Snapey! Thank you for spotting that mistake. I changed the key from "id" to "author_id" and its working perfectly now. What a change 7 characters can make. Thanks again, and here is the correct code to help anyone later down the line:

Old Code:

  public function author() {
    return $this->belongsTo('App\Models\Author', 'id');
  }

Updated Working Code:

  public function author() {
    return $this->belongsTo('App\Models\Author', 'author_id');
  }

Please or to participate in this conversation.