Insert Data (Many-to-Many) using Laravel

min read

Day 21 #100DaysOfCode : Học và tìm hiểu thêm mỗi ngày, lúc này covid , dịch bệnh quá, ở nhà tìm hiểu thêm, lưu trữ tại đây, có khi cần tới

//model User
public function roles(){
	$this->belongsToMany("User::class","user_role");
}
//model Role
public function users(){
	$this->belongsToMany("Role::class","user_role");
}

Tạo template blade cho form 

//form.blade.php
<select name="role">
	<option value="1">Admin</option>
	<option value="2">Member</option>
</select>

//controller
Nhận Request từ form, trong file điều khiển ta có thể nhận như sau

$role = $request->role //get value from select option in form.blade.php

$user = User::create($request->only('required fields ...')); //add data to table "users"

$user->roles()->attach($role);  //add data many to many in table user_role

Ví dụ cấu hình nó trong function register()

public function register (Request $request){
    $role = $request->role;
    $user = User::create($request->only('required fields'));
    $user->roles()->attach($role or $request->role); 

}

Lấy thông tin user theo id, sau đó tìm lấy role của user đó

use App\User;

$user = User::find(1);

foreach ($user->roles as $role) {
    
	echo $role->Name;// name role
}

Xóa mối quan hệ nhiều nhiều (many-to-many)

$user->roles()->detach();

$user->roles()->detach($roleId);

//or

$user = User::find(1);

$user->roles()->detach([1, 2, 3]);