I have two models (User and Services). What I want is to display all the services of a user. This is my action that show me all the services :
public function index()
{
$services = Service::all();
// load the view and pass the nerds
return View::make('services.index')->with('services', $services);
}
and in my User model I add this function :
public function service()
{
return $this->hasMany('Service');
}
Then in my service model :
public function user()
{
return $this->hasOne('User');
}
So please if someone has any idea, I will be very appreciative :)
The relationships you are looking for for a 1-to-many relationship are hasMany()
and belongsTo()
.
With that in mind, in your Service
model, define the relationship like so...
public function user()
{
return $this->belongsTo('User');
}
It doesn't really matter too much in this scenario because you aren't using it, but it might save you some confusion later.
Now to get the users's services, you can use the User
model.
$services = User::find(1)->services;
Or if you just want to get the logged in users's services...
$services = Auth::user()->services;