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

princeoo7's avatar

Eager Loading, 2 out of 3 returned as null

i have the following code:

article controller

$records = Article::where(['status' => 1])->with(['author', 'meta', 'tags'])->orderBy('id', 'DESC')->paginate(20);

article model

<?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Article extends Model
    {
         public $timestamps = true;

            public function author()
            {
         return $this->belongsTo(User::class);
            }

            public function meta()
            {
                return $this->HasOne(MetaData::class, 'article_id');
            }

            public function tags()
            {
                return $this->belongsTo(Tag::class);
         }
    }

and this is what i get on dd()

 #relations: array:3 [▼
      "author" => null
      "meta" => MetaData {#455 ▶}
      "tags" => null
    ]

author and tags are nulled for some reason.

0 likes
12 replies
JohnBraun's avatar

It sounds like you want to define your relationship with Tags as hasMany or belongsToMany (many-to-many) instead of belongsTo. Use hasMany if you have specific tags for each post. If you want to reuse tags amongst posts, create a belongsToMany relationship. See https://laravel.com/docs/5.8/eloquent-relationships.

Furthermore, make sure your articles table has an 'author_id' column or specify you want to use a different foreign key. From the Laravel docs: "Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id.".

public function author()
{
  return $this->belongsTo(User::class, 'user_id');
}

public function tags()
{
  //  return $this->hasMany(Tag::class);
  return $this->belongsToMany(Tag::class);
}
1 like
princeoo7's avatar

@JOHNBRAUN - i did made the change as it was a typo on my part but i am just getting the below output

"author" => User {#441 ▶}
      "meta" => MetaData {#469 ▶}
      "tags" => Collection {#471 ▼
        #items: array:1 [▼
          0 => Tag {#508 …26}
        ]
      }

now what does 0 => Tag {#508 …26} represent ? any clue ?

princeoo7's avatar

Ok just got the dd() removed and saw that the data was passed. my back i shall have checked it prior commenting it.

JohnBraun's avatar

@PRINCEOO7 - Which typo did you fix?

You have a collection of tags, containing 1 Tag object (noted by Tag{#508 ...26}).

princeoo7's avatar

@JOHNBRAUN - typo in the sense in the belongsToMany I forgot Many ;)

but author is same and started working itself. weird :/

princeoo7's avatar

how does @jeffery gets the following code get working ?

TagModel

class Tag extends Model
{
        public function articles()
        {
            return $this->belongsToMany(Article::class);
        }

        public function getRouteKeyName()
        {
            return 'name';
        }
}

and TagController

public function index(Tag $tag)
    {
        return $tag;
 }

web.php

Route::get('/blog/tag/{name}', 'TagsController@index')->name('blogs.showbyTag');

referencing to laracasts video for Laravel From Scratch: Part 31 - Sorting Posts By Tags

https://www.youtube.com/watch?v=Lq9rOAYW-S0

i get nothing. blank and jeffery gets an output :/

@JOHNBRAUN any idea ?

princeoo7's avatar

@JOHNBRAUN - i solved that but now i am not able to get the reverse properly.

means i have the following code in the Tag model,

class Tag extends Model
{
    public function articles()
    {
        return $this->belongsToMany(Article::class);
    }

    public function getRouteKeyName()
 {
        return 'name';
    
}

and in Tag controller :

public function index(Tag $tag)
    {
     return $tag;
    }

in jeffery video 30 for laravel from scratch it works but for me it's not working.

if i do :

Tag::with('articles')->get();

it works but only article is retrived and not tag > article > author + tags + meta where as i was expecting tag > article > author + tags + meta.

this is find of confusing right now for me as i am still learning this stuff.

JohnBraun's avatar

@PRINCEOO7 - Add a $with property to your Article model, mentioning the models you'll want to eager load whenever you fetch an Article from the database.

<?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Article extends Model
    {
         protected $with = ['author', 'tags', 'meta'];

         // ...
    }
JohnBraun's avatar

@prince007 By the way, it might be a good idea to create a new topic for each new question which is not related to your initial question related to 'eager loading 2 out of 3 returned as null'.

Snapey's avatar

both of these

$records = $tag::with('articles')->paginate(20);
// or
$records = $tag->load('articles')->paginate(20);

return paginated list of tag with articles as a child relationship

what you need is to use the articles function on the tag model

$records = $tag->articles()->paginate(20);

Please or to participate in this conversation.