many to many laravel example
Example 1: one to many laravel
For example, a blog post may have an infinite number of comments. And a single
comment belongs to only a single post
class Post extends Model
{
public function comments()
{
return $this->hasMany('App\Models\Comment');
}
}
class Comment extends Model
{
public function post()
{
return $this->belongsTo('App\Models\Post');
}
}
Example 2: laravel pivot table model
/*Model - Service*/
public function customer(){
return $this->belongsToMany('customer')->withPivot(
'start_date',
'stop_date',
'rem_date',
'due_date',
'status'
);
}
/*Model - customer*/
public function services(){
return $this->belongsToMany('Service')->withPivot(
'start_date',
'stop_date',
'rem_date',
'due_date',
'status'
);
}
////These following relations didnt workout
/*Model - custserv*/ //uses the pivot table customer_service//
public function staff(){
return $this->belongsToMany('Staff');
}
/*Model - Staff*/
public function custservs(){
return $this->belongsToMany('Custserv');
}
/*schema for pivot table 'staff' and 'Custserv' */
Schema::create('customer_service_user', function(Blueprint $table)
{
$table->increments('id');
$table->integer('customer_service_id')->unsigned()->index();
$table->foreign('customer_service_id')->references('id')->on('customer_service')->onDelete('cascade');
$table->integer('staff_id')->unsigned()->index();
$table->foreign('staff_id')->references('id')->on('staff')->onDelete('cascade');
$table->timestamps();
});
Example 3: many to many relationship laravel
use App\Models\User;
$user = User::find(1);
$user->roles()->attach($roleId);
Example 4: laravel many to many relationship
/*
users
id - integer
name - string
roles
id - integer
name - string
role_user
user_id - integer
role_id - integer
*/
class User extends Model
{
/**
* The roles that belong to the user.
*/
public function roles()
{
/*To determine the table name of the relationship's intermediate
table, Eloquent will join the two related model names in
alphabetical order. However, you are free to override this
convention. You may do so by passing a second argument to the
belongsToMany method*/
return $this->belongsToMany(Role::class,'role_user');
}
}
//Defining The Inverse Of The Relationship
class Role extends Model
{
/**
* The users that belong to the role.
*/
public function users()
{
return $this->belongsToMany(User::class);
}
}