Are those harvests will null users actually have users attached to them?
Aug 22, 2023
2
Level 1
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
Please or to participate in this conversation.