user1875774
user1875774

Reputation: 53

Laravel5: Many to many relationship

I have just started laravel5, but i haven't seen the model folder just like laravel4. My questions are.

1.Where model folder reside in laravel5?

2.How many to manay relationship handle in laravel5?

I have the following scenario.

Role Table fields . id . role_name

User Table . id . username . email . password

pivot table role_user . id . role_id . user_id

Upvotes: 0

Views: 219

Answers (3)

DengDeng
DengDeng

Reputation: 543

The model files are in app directory. When you install a fresh laravel, you should see a User.php file under app directory.

In your Role model, you should define a function:

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

In your User model, you should define a function:

public function roles(){
    return $this->belongsToMany('App\Role');
}

And if you want to get roles which belongs to user(s):

foreach($users as $user){
    $roles = $user->roles;
}

If you want to get users under one role:

$users = $role->users;

foreach($users as $user){
    //
}

These are "lazy loading", only load relationships when you access them.

Here for more about model
Here for more about relationships

Upvotes: 0

Naing Win
Naing Win

Reputation: 1256

Your application model should be like this > app/Model/Role.php

Set namespace App\Model; to all model files under app/Model.

Many to Many Relationship

User.php

public function roles()
{
     return $this->belongsToMany('App\Model\Role');
}

Role.php

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

Now you can use like this

$user = App\User::find(1);

foreach ($user->roles as $role) 
{
    //
}

Upvotes: 0

Matt Burrow
Matt Burrow

Reputation: 11067

  1. There is not one. Models reside in the App/ folder. As this is where the User model resides. Create your own folder to have one.
  2. The documentation will cover this, found here. This will go through how the relationship is set up within your relevant model.

    public function roles(){  
        return $this->belongsToMany('App\Role', 'Pivot_table_name', 'foreign_key', 'other_key');  
    }
    

Please Note: Pretty much everything is covered within the documentation.

Now that you have your relation, you can call it like so on your user model $user = User::with('roles')->find(1); This will eager load your role on to the model for you, and can be accessed like so; $user->roles.

The documentation also covers querying relationships using the whereHas method found here.

Upvotes: 1

Related Questions