This is the third blog post of Laravel relationship Model tutorial series. In this tutorial, we are going to learn how to implement Many to Many relationship within our Laravel application
Prerequisites
Laravel
To Continue with this tutorial, you should have installed Laravel in your pc. If you are still not installed Laravel in your machine you can configure it from here.
Setting up the Project
First you need to create a new laravel project by running below command in your terminal
<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The roles that belong to the user. */ public function roles() { return $this->belongsToMany(Role::class, 'role_user'); } }
Role Model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Role extends Model { /** * The users that belong to the role. */ public function users() { return $this->belongsToMany(User::class, 'role_user'); } }
UserRole Model:
1 2 3 4 5 6 7 8 9 10
<?php namespace App; use Illuminate\Database\Eloquent\Model; class UserRole extends Model { }
In this tutorial, we learn how to implement Many to Many relationship within Laravel. If you have any issue regarding this tutorial, mention your issue in comment section or reach me through my E-mail.