K
K
Konstantin2018-12-08 19:52:34
Laravel
Konstantin, 2018-12-08 19:52:34

Relationship with Auth()->user() for the experienced?

Why can't load the data model for Auth()->user()?
Model Users:

public function Organization()
{
    return $this->hasOne(\App\Organization::class, 'User_Id', 'id');
}

Organization model :
public function User()
{
    return $this->belongsTo(\App\User::class, 'id', 'User_Id');
}

Call:
$organization = Auth()->user();
$organization->load('Organization');
dd($organization->Organization()->get());

Result:
Collection {#415
  #items: []
}

The keys in the relations between the models are correct - I checked, also in the two tables there are related records by id = User_Id
Why then an empty collection is always returned?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Konstantin B., 2018-12-08
@Junart1

This is how you write what you want to write. According to the idea, if everything is done correctly, you should bring the organization

$user = Auth()->user();
$user->load('Organization');
dd($user->Organization);

M
Maxim Litvinov, 2018-12-08
@Max-GopheR

load() is lazy loading. This means that you must have a collection in your $organization before using load.
And something tells me it's not.
Maybe I misunderstood something in your code, then here is a link to the documentation: https://laravel.ru/docs/v5/eloquent-relationships#...

A
Arthur, 2018-12-08
@ART_CORP

$organization = Auth()->user();
is everything okay here? get a user?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question