0
votes

I'm trying to create a relationship between two models. My first model is the User Model, the second one is Company.

I tried adding in the User model the hasMany('App\Comapny') property, and in the Company one, belongsTo('App\User').

// In User Model

public function companies(){
    return $this->hasMany('App\Company');
}

// In Company Model

public function user(){
    return $this->belongsTo('App\User');
}

// And in the controller:

$user_id = auth()->user('id');
$user = User::find($user_id); 
return view('devices.show')->with('companies', $user->companies);

It should return an array with all the companies that my User has when using "$user->comapnies", however, it returns this message instead:

Property [companies] does not exist on this collection instance.

Thanks, any help is welcome

2

2 Answers

0
votes

Thanks for the quick response. I figured it out, the problem was this line:

$user_id = auth()->user('id');

It should be instead

$user_id = auth()->user()->id;
0
votes

Try this,

$user_id = auth()->user->id;
$user = User::with('companies')->where('id', $user_id)->first(); 
return view('devices.show', compact('user'));

Then you can access the company relation with $user->company[index]-> in the view.