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

HT-ftw's avatar

Relations with() method not working

Hello Everyone, I'm on Laravel 10, with Livewire 3. I have two tables in my DB:

users (id, name)
harvests (id, tonnes, user_id)

I have two models:

User
Harvest

Within Harvest model I have a belongsTo relation:

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

using the above relation like so:

$harvests = Harvest::get();
foreach($harvests as $harvest)
{
 echo $harvest->user->name;
}

works as intended however when I try to use with(); in order to benefit from Eager Loading:

$harvests = Harvest::with('user')->get();
foreach($harvests as $harvest)
{
 dd($harvest->user);
}

I get null. From my understanding I should be able to get attributes like id or name in my case. Can anyone help me out and tell me what I am missing? Thanks HT

0 likes
2 replies
kevinbui's avatar

Are those harvests will null users actually have users attached to them?

HT-ftw's avatar

@kevinbui Yes they do, there are no harvests will null user if there is a harvest there s always a user attached, I'm quite confused because if I check the queries:

DB::connection()->enableQueryLog();
$harvests = Harvest::with('user')->get();
dd(DB::getQueryLog());

the queries seam to be correct:

array:2 [▼ // app/Livewire/Harvests/Harvests.php:219
  0 => array:3 [▼
    "query" => "select * from `harvests`"
    "bindings" => []
    "time" => 12.77
  ]
  1 => array:3 [▼
    "query" => "select * from `users` where `users`.`id` in (12, 15, 16, 18, 19, 22, 23, 24, 25, 27)"
    "bindings" => []
    "time" => 0.62
  ]
]

using join() works as well

Please or to participate in this conversation.