😎Laravel 9 Many to Many Eloquent Relationship Tutorial, full (ok)

https://www.itsolutionstuff.com/post/laravel-9-many-to-many-eloquent-relationship-tutorialexample.html

Một chú ý rất quan trọng sử dụng belongsTo

Trường hợp 1 sử dụng product_id làm khóa phụ

Trường hợp 2 sử dụng order_id làm khóa phụ

Dùng find sao một số trường hợp không ra kết quả?

C:\xampp\htdocs\hanam\resources\views\admin\show_order_detail.blade.php

Câu trả lời: Không giống như ‘Where’ giúp bạn lấy bất kỳ trường cơ sở dữ liệu hợp lệ nào, find chỉ sử dụng khóa chính được đăng ký theo mặc định trong hệ thống để truy xuất dữ liệu đơn lẻ từ cơ sở dữ liệu.

Ví dụ 1

Source Code:

10MB
test.rar

Bên này sử dụng cho các ví dụ One to One, One to Many

C:\xampp\htdocs\test\routes\web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
use App\Http\Controllers\PostController ;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('test', [UserController::class, 'index']);// One to One
Route::get('/', [PostController::class, 'index']);// One to Many, Many To Many

Ví dụ 1: cho mối quan hệ 1-1 C:\xampp\htdocs\test\app\Http\Controllers\UserController.php

<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Models\Phone;
use Illuminate\Http\Request;
class UserController extends Controller {
  /**
   * Write code on Method
   *
   * @return response()
   */
  public function index(Request $request) {
    // One to One
    // $phone = User::find(1)->phone;
    // echo $phone->id;
    // echo "<br/>";
    // echo $phone->user_id;
    // echo "<br/>";
    // echo $phone->phone;
    $user = Phone::find(1)->user;
    echo $user->id;
    echo "<br/>";
    echo $user->name;
    echo "<br/>";
    echo $user->email;
  }
}

C:\xampp\htdocs\test\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use App\Models\Post;
use App\Models\Comment;
use App\Models\User;
use App\Models\Role;
use Illuminate\Http\Request;
class PostController extends Controller {
  /**
   * Write code on Method
   *
   * @return response()
   */
  public function index(Request $request) {
    // == One to Many Retrieve Records ==
    // $comments = Post::find(3)->comments;
    // foreach ($comments as $comment) {
    //     echo $comment->id;
    //     echo "<br/>";
    //     echo $comment->post_id;
    //     echo "<br/>";
    //     echo $comment->comment;
    //     echo "<br/>";
    //     echo "========";
    //     echo "<br/>";
    // }
    // $post = Comment::find(1)->post;
    // echo $post->id;
    // echo "<br/>";
    // echo $post->post_id;
    // echo "<br/>";
    // $title = Post::find($post->post_id);
    // echo $title->name;
    // echo "<br/>";
    // echo $post->comment;
    // echo "<br/>";
    // == One to Many Create Records ==
    // $post = Post::find(1);
    // $comment = new Comment();
    // $comment->comment = "Hi ItSolutionStuff.com";
    // $post = $post->comments()->save($comment);
    // == One to Many Create Records ==
    // $post = Post::find(1);
    // $comment1 = new Comment();
    // $comment1->comment = "Hi ItSolutionStuff.com Comment 1";
    // $comment2 = new Comment();
    // $comment2->comment = "Hi ItSolutionStuff.com Comment 2";
    // $post = $post->comments()->saveMany([$comment1, $comment2]);
    // == One to Many Create Records ==
    // $comment = Comment::find(1);
    // $post = Post::find(22);
    // $comment->post()->associate($post)->save(); Nó giống với update_post_meta trong wordpress nó cập nhât meta_id, post_id
    // == Many to Many Retrieve Records ==
    // $user = User::find(30);
    // $roles = $user->roles;
    // foreach ($roles as $role) {
    //   echo $role->id;
    //   echo "<br/>";
    //   echo $role->name;
    //   echo "<br/>";
    //   echo "=========";
    //   echo "<br/>";
    // }
    // == Many to Many Create Records ==
    // $role = Role::find(1);  
    // dd($role->users);
    // == Mối quan hệ cấp 3 Method attach ==
    // $user = User::find(30);  
    // $roleIds = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]; 
    // $user->roles()->attach($roleIds); // insert into `role_user` (`role_id`, `user_id`) values (1, 30), (11, 30))
    // $role = Role::find(1);  
    // $userIds = [10, 11]; // => insert into `role_user` (`role_id`, `user_id`) values (1, 10), (1, 11))
    // $role->users()->attach($userIds);
    // ==  Mối quan hệ cấp 3 Method sync ==
    // $user = User::find(30);  
    // $roleIds = [1, 2];
    // $user->roles()->sync($roleIds); // Giờ theo dõi bảng chúng chỉ có quyền 1,2 mà thôi :) do ta dùng sync
  }
}

C:\xampp\htdocs\test\app\Models\Comment.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model {
  use HasFactory;
  public function post() {
    return $this->belongsTo(Comment::class,'post_id','id');
  }
}

C:\xampp\htdocs\test\app\Models\Phone.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model {
  use HasFactory;
  /**
   * Get the user that owns the phone.
   *
   * Syntax: return $this->belongsTo(User::class, 'foreign_key', 'owner_key');
   *
   * Example: return $this->belongsTo(User::class, 'user_id', 'id');
   */
  // public $timestamps = false;
  // protected $table = 'phones';
  // protected $primaryKey = 'id';
  protected $fillable = [
    'user_id', 'phone'
  ];
  public function user() {
    return $this->belongsTo(User::class,'user_id', 'id');
  }
}

C:\xampp\htdocs\test\app\Models\Post.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
  use HasFactory;
  public function comments() {
    return $this->hasMany(Comment::class);
  }
}

C:\xampp\htdocs\test\app\Models\Role.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Role extends Model {
  use HasFactory;
  /**
   * The users that belong to the role.
   */
  public function users() {
    return $this->belongsToMany(User::class, 'role_user');
  }
}

C:\xampp\htdocs\test\app\Models\User.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable {
  use HasApiTokens, HasFactory, Notifiable;
  /**
   * The attributes that are mass assignable.
   *
   * @var array<int, string>
   */
  protected $fillable = [
    'name',
    'email',
    'password',
  ];
  /**
   * The attributes that should be hidden for serialization.
   *
   * @var array<int, string>
   */
  protected $hidden = [
    'password',
    'remember_token',
  ];
  /**
   * The attributes that should be cast.
   *
   * @var array<string, string>
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
  ];
  /**
   * Get the phone associated with the user.
   *
   * Syntax: return $this->hasOne(Phone::class, 'foreign_key', 'local_key');
   *
   * Example: return $this->hasOne(Phone::class, 'user_id', 'id');
   */
  public function phone() {
    return $this->hasOne(Phone::class, 'user_id', 'id');
  }
  /**
   * The roles that belong to the user.
   */
  public function roles() {
    return $this->belongsToMany(Role::class, 'role_user');
  }
}

C:\xampp\htdocs\test\app\Models\UserRole.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class UserRole extends Model {
  use HasFactory;
  public $timestamps    = false;
  protected $table      = 'role_user';
  protected $fillable = [
    'user_id', 'role_id'
  ];
}

C:\xampp\htdocs\test\database\factories\CommentFactory.php

<?php
namespace Database\Factories;
use App\Models\Comment;
use Illuminate\Database\Eloquent\Factories\Factory;
class CommentFactory extends Factory {
  protected $model = Comment::class;
  /**
   * Define the model's default state.
   *
   * @return array
   */
  public function definition() {
    return [
      'post_id' => $this->faker->numberBetween(1,500),
      'comment'  => $this->faker->text(100),
    ];
  }
}

C:\xampp\htdocs\test\database\factories\PhoneFactory.php

<?php
namespace Database\Factories;
use App\Models\Phone;
use Illuminate\Database\Eloquent\Factories\Factory;
class PhoneFactory extends Factory {
  protected $model = Phone::class;
  /**
   * Define the model's default state.
   *
   * @return array
   */
  public function definition() {
    return [
      'user_id' => $this->faker->numberBetween(1, 30),
      'phone'   => $this->faker->phoneNumber,
    ];
  }
}

C:\xampp\htdocs\test\database\factories\PostFactory.php

<?php
namespace Database\Factories;
use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
class PostFactory extends Factory {
  protected $model = Post::class;
  /**
   * Define the model's default state.
   *
   * @return array
   */
  public function definition() {
    return [
      'name' => $this->faker->text(10),
    ];
  }
}

C:\xampp\htdocs\test\database\factories\RoleFactory.php

<?php
namespace Database\Factories;
use App\Models\Role;
use Illuminate\Database\Eloquent\Factories\Factory;
class RoleFactory extends Factory {
  protected $model = Role::class;
  /**
   * Define the model's default state.
   *
   * @return array
   */
  public function definition() {
    return [
      'name' => $this->faker->text(6)
    ];
  }
}

C:\xampp\htdocs\test\database\factories\UserFactory.php

<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class UserFactory extends Factory {
  /**
   * Define the model's default state.
   *
   * @return array
   */
  public function definition() {
    return [
      'name'              => $this->faker->name(),
      'email'             => $this->faker->unique()->safeEmail(),
      'email_verified_at' => now(),
      'password'          => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
      'remember_token'    => Str::random(10),
    ];
  }
  /**
   * Indicate that the model's email address should be unverified.
   *
   * @return \Illuminate\Database\Eloquent\Factories\Factory
   */
  public function unverified() {
    return $this->state(function (array $attributes) {
      return [
        'email_verified_at' => null,
      ];
    });
  }
}

C:\xampp\htdocs\test\database\factories\UserRoleFactory.php

<?php
namespace Database\Factories;
use App\Models\UserRole;
use Illuminate\Database\Eloquent\Factories\Factory;
class UserRoleFactory extends Factory {
  protected $model = UserRole::class;
  /**
   * Define the model's default state.
   *
   * @return array
   */
  public function definition() {
    return [
      'user_id' => $this->faker->numberBetween(1,30),
      'role_id' => $this->faker->numberBetween(1,5)
    ];
  }
}

C:\xampp\htdocs\test\database\migrations\2014_10_12_000000_create_users_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('users', function (Blueprint $table) {
      $table->id();
      $table->string('name');
      $table->string('email')->unique();
      $table->timestamp('email_verified_at')->nullable();
      $table->string('password');
      $table->rememberToken();
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('users');
  }
}

C:\xampp\htdocs\test\database\migrations\2014_10_12_100000_create_password_resets_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePasswordResetsTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('password_resets', function (Blueprint $table) {
      $table->string('email')->index();
      $table->string('token');
      $table->timestamp('created_at')->nullable();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('password_resets');
  }
}

C:\xampp\htdocs\test\database\migrations\2019_08_19_000000_create_failed_jobs_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFailedJobsTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('failed_jobs', function (Blueprint $table) {
      $table->id();
      $table->string('uuid')->unique();
      $table->text('connection');
      $table->text('queue');
      $table->longText('payload');
      $table->longText('exception');
      $table->timestamp('failed_at')->useCurrent();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('failed_jobs');
  }
}

C:\xampp\htdocs\test\database\migrations\2019_12_14_000001_create_personal_access_tokens_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePersonalAccessTokensTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('personal_access_tokens', function (Blueprint $table) {
      $table->id();
      $table->morphs('tokenable');
      $table->string('name');
      $table->string('token', 64)->unique();
      $table->text('abilities')->nullable();
      $table->timestamp('last_used_at')->nullable();
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('personal_access_tokens');
  }
}

C:\xampp\htdocs\test\database\migrations\2022_05_05_171115_create_phones_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePhonesTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('phones', function (Blueprint $table) {
      $table->id();
      $table->foreignId('user_id')->constrained('users');
      $table->string('phone');
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('phones');
  }
}

C:\xampp\htdocs\test\database\migrations\2022_05_05_180005_create_posts_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('posts', function (Blueprint $table) {
      $table->id();
      $table->string("name");
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('posts');
  }
}

C:\xampp\htdocs\test\database\migrations\2022_05_05_180155_create_comments_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCommentsTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('comments', function (Blueprint $table) {
      $table->id();
      $table->foreignId('post_id')->constrained('posts');
      $table->string("comment");
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('comments');
  }
}

C:\xampp\htdocs\test\database\migrations\2022_05_06_020336_create_roles_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRolesTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('roles', function (Blueprint $table) {
      $table->id();
      $table->string('name');
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('roles');
  }
}

C:\xampp\htdocs\test\database\migrations\2022_05_06_020431_create_role_user_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRoleUserTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('role_user', function (Blueprint $table) {
      $table->foreignId('user_id')->constrained('users');
      $table->foreignId('role_id')->constrained('roles');
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('role_user');
  }
}

C:\xampp\htdocs\test\database\seeders\CommentSeeder.php

<?php
namespace Database\Seeders;
use App\Models\Comment;
use Illuminate\Database\Seeder;
class CommentSeeder extends Seeder {
  /**
   * Run the database seeds.
   *
   * @return void
   */
  public function run() {
    Comment::factory()->count(5000)->create();
  }
}

C:\xampp\htdocs\test\database\seeders\PhoneSeeder.php

<?php
namespace Database\Seeders;
use App\Models\Phone;
use Illuminate\Database\Seeder;
class PhoneSeeder extends Seeder {
  /**
   * Run the database seeds.
   *
   * @return void
   */
  public function run() {
    Phone::factory()->count(30)->create();
  }
}

C:\xampp\htdocs\test\database\seeders\PostSeeder.php

<?php
namespace Database\Seeders;
use App\Models\Post;
use Illuminate\Database\Seeder;
class PostSeeder extends Seeder {
  /**
   * Run the database seeds.
   *
   * @return void
   */
  public function run() {
    Post::factory()->count(500)->create();
  }
}

C:\xampp\htdocs\test\database\seeders\RoleSeeder.php

<?php
namespace Database\Seeders;
use App\Models\Role;
use Illuminate\Database\Seeder;
class RoleSeeder extends Seeder {
  /**
   * Run the database seeds.
   *
   * @return void
   */
  public function run() {
    Role::factory()->count(5)->create();
  }
}

C:\xampp\htdocs\test\database\seeders\UserRoleSeeder.php

<?php
namespace Database\Seeders;
use App\Models\UserRole;
use Illuminate\Database\Seeder;
class UserRoleSeeder extends Seeder {
  /**
   * Run the database seeds.
   *
   * @return void
   */
  public function run() {
    UserRole::factory()->count(500)->create();
  }
}

C:\xampp\htdocs\test\database\seeders\UserSeeder.php

<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Seeder;
class UserSeeder extends Seeder {
  /**
   * Run the database seeds.
   *
   * @return void
   */
  public function run() {
    User::factory()->count(30)->create();
  }
}

Ví dụ 2.1: Many to Many

app\Http\Controllers\UserController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller {
  public function index(Request $request) {
    $user = User::find(2)->roles;
    dd($user);
  }
}

app\Models\Role.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
    use HasFactory;
    public function users()
    {
        return $this->belongsToMany(User::class, 'role_user');
    }
}

app\Models\User.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable {
  use HasApiTokens, HasFactory, Notifiable;
  /**
   * The attributes that are mass assignable.
   *
   * @var array<int, string>
   */
  protected $fillable = [
    'name',
    'email',
    'password',
  ];
  /**
   * The attributes that should be hidden for serialization.
   *
   * @var array<int, string>
   */
  protected $hidden = [
    'password',
    'remember_token',
  ];
  /**
   * The attributes that should be cast.
   *
   * @var array<string, string>
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
  ];
   /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_user');
    }
}

database\migrations\2022_08_24_112636_create_table_role_user_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTableRoleUserTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('role_user', function (Blueprint $table) {
            $table->foreignId('user_id')->constrained('users');
            $table->foreignId('role_id')->constrained('roles');
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('role_user');
    }
}

database\migrations\2022_08_24_112543_create_table_roles_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTableRolesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('roles');
    }
}

database\seeders\RoleSeeder.php

<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\Role;
class RoleSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Role::factory()->count(6)->create();
    }
}

database\factories\RoleFactory.php

<?php
namespace Database\Factories;
use App\Models\Role;
use Illuminate\Database\Eloquent\Factories\Factory;
class RoleFactory extends Factory
{
    protected $model = Role::class;
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name'            => $this->faker->text,
        ];
    }
}

Ví dụ 2.2: Many to Many

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
    public function index(Request $request) {
        $user = User::find(6)->roles;
        dd($user);
    }
}

Ví dụ 2.3: Many To Many

app\Http\Controllers\UserController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Role;
class UserController extends Controller
{
    public function index(Request $request) {
        // $user = User::find(6)->roles;
        // dd($user);
        $role = Role::find(1);
        dd($role->users);
    }
}

Ví dụ 2.4.1: Many To Many lấy giá trị trung gian (Theo mặc định, chỉ có các keys sẽ có mặt trên các pivot object.) đọc thêm

Kết quả:

Nếu bạn muốn bảng pivot của bạn tự động có created_at và updated_at timestamps, sử dụng các phương thức Timestamps vào trong định nghĩa của mối quan hệ:

C:\xampp8\htdocs\testauth\app\Models\User.php

return $this->belongsToMany(Role::class,'role_user','user_id','role_id')->withTimestamps();

C:\xampp8\htdocs\testauth\database\migrations\2023_01_04_101502_create_roles_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
    Schema::create('roles', function (Blueprint $table) {
      $table->id();
      $table->string('name');
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    Schema::dropIfExists('roles');
  }
};

C:\xampp8\htdocs\testauth\database\migrations\2023_01_04_101537_create_role_user_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
    Schema::create('role_user', function (Blueprint $table) {
      $table->id();
      $table->integer('user_id');
      $table->integer('role_id');
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    Schema::dropIfExists('role_user');
  }
};

C:\xampp8\htdocs\testauth\database\factories\RoleFactory.php

<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Role>
 */
class RoleFactory extends Factory
{
  /**
   * Define the model's default state.
   *
   * @return array<string, mixed>
   */
  public function definition()
  {
    return [
      'name' => fake()->name(),
    ];
  }
}

C:\xampp8\htdocs\testauth\database\factories\RoleUserFactory.php

<?php
namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Model>
 */
class RoleUserFactory extends Factory
{
  private static $order = 1;
  private static $order2 = 1;
  /**
   * Define the model's default state.
   *
   * @return array<string, mixed>
   */
  public function definition()
  {
    return [
      'user_id' => self::$order++,
      'role_id' => self::$order2++,
    ];
  }
}

C:\xampp8\htdocs\testauth\database\seeders\DatabaseSeeder.php

<?php
namespace Database\Seeders;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\User;
use App\Models\Role;
use App\Models\RoleUser;
class DatabaseSeeder extends Seeder
{
  /**
   * Seed the application's database.
   *
   * @return void
   */
  public function run()
  {
    User::factory(10)->create();
    Role::factory(10)->create();
    RoleUser::factory(10)->create();
  }
}

C:\xampp8\htdocs\testauth\app\Http\Controllers\UserController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
  public function getRoles()
  {
    $user = User::find(1);
    foreach ($user->roles as $role) {
      echo $role->pivot->created_at;
    }
  }
}

C:\xampp8\htdocs\testauth\routes\web.php

<?php
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
    return view('welcome');
});
Route::get('/user', [UserController::class,'getRoles']);

Ví dụ 2.4.2: Many To Many lọc giá trị trong bảng trung gian (Đọc thêm)

C:\xampp8\htdocs\testauth\app\Models\User.php

<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
  use HasApiTokens, HasFactory, Notifiable;
  /**
   * The attributes that are mass assignable.
   *
   * @var array<int, string>
   */
  protected $fillable = [
    'name',
    'email',
    'password',
  ];
  /**
   * The attributes that should be hidden for serialization.
   *
   * @var array<int, string>
   */
  protected $hidden = [
    'password',
    'remember_token',
  ];
  /**
   * The attributes that should be cast.
   *
   * @var array<string, string>
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
  ];
  /**
   * The roles that belong to the user.
   */
  public function roles()
  {
    return $this->belongsToMany(Role::class,'role_user','user_id','role_id')->withPivot('created_at')->wherePivotIn('created_at', ['2023-01-04 10:35:33', '2023-01-04 10:35:32']);
  }
}

Kết quả:

Laravel 9 Many to Many Eloquent Relationship Tutorial

By Hardik Savani March 28, 2022 Category : LaravelPauseUnmuteLoaded: 2.69%FullscreenVDO.AIHi,

Today our leading topic is many to many relationship laravel 9. I would like to share with you laravel 9 many to many relationship example. This tutorial will give you a simple example of laravel 9 belongstomany tutorial. This tutorial will give you simple example of laravel 9 many to many sync.

So in this tutorial, you can understand how to create many-to-many relationships with migration with a foreign key schema for one to many relationships, use sync with a pivot table, create records, attach records, get all records, delete, update, where condition and everything related to many to many relationship.

In this example, i will create "users", "roles" and "role_user" tables. each table is connected with each other. now we will create many to many relationships with each other by using the laravel Eloquent Model. We will first create database migration, then model, retrieve records and then how to create records too. So you can also see the database table structure on the below screen.

Many to Many Relationship will use "belongsToMany()" for relation.

Create Migrations:

Now we have to create migration of "users", "roles" and "role_user" table. we will also add foreign key with users and roles table. so let's create like as below:

users table migration:

<?php  use Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema;  return new class extends Migration{    /**     * Run the migrations.     *     * @return void     */    public function up()    {        Schema::create('users', function (Blueprint $table) {            $table->id();            $table->string('name');            $table->string('email')->unique();            $table->timestamp('email_verified_at')->nullable();            $table->string('password');            $table->rememberToken();            $table->timestamps();        });    }    /**     * Reverse the migrations.     *     * @return void     */    public function down()    {        Schema::dropIfExists('users');    }};

roles table migration:

<?php  use Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema;  return new class extends Migration{    /**     * Run the migrations.     *     * @return void     */    public function up()    {        Schema::create('roles', function (Blueprint $table) {            $table->id();            $table->string('name');            $table->timestamps();        });    }      /**     * Reverse the migrations.     *     * @return void     */    public function down()    {        Schema::dropIfExists('roles');    }};

role_user table migration:

<?php  use Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema;  return new class extends Migration{    /**     * Run the migrations.     *     * @return void     */    public function up()    {        Schema::create('role_user', function (Blueprint $table) {            $table->foreignId('user_id')->constrained('users');            $table->foreignId('role_id')->constrained('roles');        });    }    /**     * Reverse the migrations.     *     * @return void     */    public function down()    {           Schema::dropIfExists('role_user');    }};

Create Models:

Here, we will create User, Role and UserRole table model. we will also use "belongsToMany()" for relationship of both model.

User Model:

<?php  namespace App\Models;  use Illuminate\Contracts\Auth\MustVerifyEmail;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Foundation\Auth\User as Authenticatable;use Illuminate\Notifications\Notifiable;use Laravel\Sanctum\HasApiTokens;  class User extends Authenticatable{    use HasApiTokens, HasFactory, Notifiable;      /**     * The attributes that are mass assignable.     *     * @var array     */    protected $fillable = [        'name',        'email',        'password',    ];      /**     * The attributes that should be hidden for serialization.     *     * @var array     */    protected $hidden = [        'password',        'remember_token',    ];      /**     * The attributes that should be cast.     *     * @var array     */    protected $casts = [        'email_verified_at' => 'datetime',    ];      /**     * The roles that belong to the user.     */    public function roles()    {        return $this->belongsToMany(Role::class, 'role_user');    }}

Role Model:

<?php  namespace App\Models;  use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;  class Role extends Model{    use HasFactory;      /**     * The users that belong to the role.     */    public function users()    {        return $this->belongsToMany(User::class, 'role_user');    }}

UserRole Model:

<?php  namespace App\Models;  use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;  class UserRole extends Model{    use HasFactory;      }

Retrieve Records:

$user = User::find(1);	 dd($user->roles);
$role = Role::find(1);	 dd($role->users);

Create Records:

$user = User::find(2);	 $roleIds = [1, 2];$user->roles()->attach($roleIds);
$user = User::find(3);	 $roleIds = [1, 2];$user->roles()->sync($roleIds);

$role = Role::find(1);	 $userIds = [10, 11];$role->users()->attach($userIds);

Read Also: Laravel 9 One to Many Eloquent Relationship Tutorial

$role = Role::find(2);	 $userIds = [10, 11];$role->users()->sync($userIds);

I hope you understand of many to many relationship...

Last updated