Question

A company hasMany users, this relationship is achieved through a pivot table. I want to be able to get the company.ID of the company an individual user is related to:

$company_id = User::find(Auth()->$id)->companies->get('$id');

Unfortunately, I have also tried the pluck() method, but to no success. How can one retrieve a specific value from a formula like this?

Était-ce utile?

La solution

in your user model you should add the relationship belongsTo (if the user belongs only to one company)

public function company(){

    return belongsTo('company');
}

then you can get the id of the company like this

$user      = User::find($id);
$company   = $user->company;
$companyId = $company->id;

I hope this will be helpful

Autres conseils

Well if the User can only be associated with one company, then your relationship should reflect this. Then you'd be able to use eager loading to do something like this:

// assumes the user is logged in
$user = Auth::user();

// assuming your relationship is set up correctly, you can do this:
echo $user->company->id;

You'd need to post the code relating to your models / relationships for a fuller answer, however.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top