Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether many-to-many relationship exists Laravel

I have the following Models:

/* Team.php */

class Team extends Eloquent {

  public function users() {
    return $this->belongsToMany('User');
  }

}

/* User.php */

class User extends Eloquent {

  public function teams() {
    return $this->hasMany('Team');
  }

}

and database structure:

teams
  id
  user_id
  name

users
  id
  email

team_user
  id
  team_id
  user_id

A user can create (and own - hence teams.user_id) a team, but also belong to other teams.

If possible, I'd like to be able to get all the teams for a particular user using Eloquent without doing a custom SQL query like so:

 SELECT teams.* 
 FROM teams 
 JOIN team_user 
 ON (team_user.team_id = teams.id) 
 WHERE team_user.user_id = ?

The custom SQL query works but I'm convinced this isn't the native way to go about this in Laravel.

Can anyone help? Thanks in advance for reading.

like image 403
Mike F Avatar asked Oct 21 '25 04:10

Mike F


1 Answers

To answer to the question in the title, here is how you define a boolean function in the user model to know if the relation exists in the pivot table 'team_user':

public function isPartOfThe($team)
{
    return $this->teams()->where('team_id', $team->id)->exists();
}

Then you can call the function in your controller as follow:

If($user->isPartOfThe($team)
{
    //true
}
like image 100
sbkl Avatar answered Oct 23 '25 02:10

sbkl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!