{"id":7901,"date":"2023-05-31T05:55:48","date_gmt":"2023-05-31T05:55:48","guid":{"rendered":"https:\/\/www.bacancytechnology.com\/qanda\/?p=7901"},"modified":"2023-08-07T05:24:49","modified_gmt":"2023-08-07T05:24:49","slug":"many-to-many-migration-in-laravel","status":"publish","type":"post","link":"https:\/\/www.bacancytechnology.com\/qanda\/laravel\/many-to-many-migration-in-laravel","title":{"rendered":"Many to Many Relationships"},"content":{"rendered":"<p>Many to many relationships will occur when we&#8217;ve 2 tables which are interconnected with each other with multiple records.<\/p>\n<p><strong>Definition:<\/strong> Many-to-many (M:M) &#8211; is used to relate many records in the table A with many records in the table B. A record (&#8216;parent&#8217;) in Table A can have many matching records (&#8216;children&#8217;) in Table B, and a record (&#8216;child&#8217;) in Table B can have many matching records (&#8216;parents&#8217;) in Table A.<\/p>\n<p>So, now we&#8217;ll be understanding about how to create a Many to Many Relationship in Laravel with migration through foreign key references and sync data with pivot table and CRUD operation for students, subjects related to Many to Many Relationship.<\/p>\n<h3>Steps are as follows:<\/h3>\n<ol>\n<li style=\"list-style-type: none;\">\n<ol>\n<li style=\"list-style-type: none;\">\n<ol>\n<li>At the very first install fresh Laravel and create a database and make environment configurations.<br \/>\n<strong>Terminal Command:<\/strong> composer create-project laravel\/laravel test-app<\/li>\n<li>Create 2 Models with migration through below commands:<br \/>\nTerminal Command: php artisan make:model Student -m<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/**\r\n * Run the migrations.\r\n *\r\n * @return void\r\n *\/\r\npublic function up()\r\n{\r\n    Schema::create('student', function (Blueprint $table){\r\n        $table-&gt;id();\r\n\r\n        $table-&gt;string('f_name')-&gt;nullable();\r\n        $table-&gt;string('l_name')-&gt;nullable();\r\n        $table-&gt;string('address')-&gt;nullable();\r\n\r\n        $table-&gt;timestamps();\r\n    });\r\n}\r\n\r\n\/**\r\n * Reverse the migrations.\r\n *\r\n * @return void\r\n *\/\r\npublic function down()\r\n{\r\n    Schema::dropIfExists('student');\r\n}<\/pre>\n<p><strong>Terminal Command:<\/strong> php artisan make:model Subject -m<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/**\r\n * Run the migrations.\r\n *\r\n * @return void\r\n *\/\r\npublic function up()\r\n{\r\n    Schema::create('subject', function (Blueprint $table){\r\n        $table-&gt;id();\r\n\r\n        $table-&gt;string('name')-&gt;nullable();\r\n\r\n        $table-&gt;timestamps();\r\n    });\r\n}\r\n\r\n\/**\r\n * Reverse the migrations.\r\n *\r\n * @return void\r\n *\/\r\npublic function down()\r\n{\r\n    Schema::dropIfExists('subject');\r\n}<\/pre>\n<\/li>\n<li><strong>Create a new pivot table:<\/strong><br \/>\nWe need to connect subjects, students both tables and which connected through a pivot table. With below terminal command pivot table migration will be created.<br \/>\n<strong>Terminal Command:<\/strong> php artisan make:migration createStudentSubjectPivotTable<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/**\r\n * Run the migrations.\r\n *\r\n * @return void\r\n *\/\r\npublic function up()\r\n{\r\n    Schema::create('student_subject', function (Blueprint $table){\r\n        $table-&gt;id();\r\n\r\n        $table-&gt;foreignId('student_id')-&gt;nullable()-&gt;constrained('student')-&gt;onUpdate('SET NULL')-&gt;onDelete('CASCADE');\r\n        $table-&gt;foreignId('subject_id')-&gt;nullable()-&gt;constrained('subject')-&gt;onUpdate('SET NULL')-&gt;onDelete('CASCADE');\r\n        $table-&gt;string('grade')-&gt;nullable();\r\n\r\n        $table-&gt;timestamps();\r\n    });\r\n}\r\n\r\n\/**\r\n * Reverse the migrations.\r\n *\r\n * @return void\r\n *\/\r\npublic function down()\r\n{\r\n    Schema::dropIfExists('student_subject');\r\n}<\/pre>\n<\/li>\n<li>Now, both models are defined through foreign references which is as follows:<br \/>\n<strong>Student model<\/strong> will be like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?php\r\n\r\nnamespace App\\Models;\r\n\r\nuse Illuminate\\Database\\Eloquent\\Factories\\HasFactory;\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\n\r\nclass Student extends Model\r\n{\r\n    use HasFactory;\r\n\r\n    protected $table = \"student\";\r\n\r\n    public function subject(){\r\n        return $this-&gt;belongsToMany(Subject::class, 'student_subject');\r\n    }\r\n}<\/pre>\n<p><strong>Subject model<\/strong> will be like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?php\r\n\r\nnamespace App\\Models;\r\n\r\nuse Illuminate\\Database\\Eloquent\\Factories\\HasFactory;\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\n\r\nclass Subject extends Model\r\n{\r\n    use HasFactory;\r\n\r\n    protected $table = \"subject\";\r\n\r\n    public function student(){\r\n        return $this-&gt;belongsToMany(Student::class, 'student_subject');\r\n    }\r\n}<\/pre>\n<\/li>\n<li>Once we\u2019ve defined the relationship, we can run the migrate to create tables in our database through below command:<br \/>\n<strong>Terminal Command:<\/strong> php artisan migrate<\/li>\n<li>Create\/Update Records:<br \/>\nNext, we need to use helper methods <strong>attach(), detach(), sync()<\/strong> which helps us to assign Many to many Relationships. For now temporary purpose I\u2019ve taken fake data for storing records, you can take your own or get it from the form submit also.<br \/>\n<strong>attach() function<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">pubilc function store (){\r\n    Subject::create([\r\n        ['name' =&gt; 'English'],\r\n        ['name' =&gt; 'Mathematics'],\r\n        ['name' =&gt; 'Science'],\r\n    ]);\r\n\r\n    $student_item = Student::create([\r\n        'f_name' =&gt; fake()-&gt;firstName(),\r\n        'l_name' =&gt; fake()-&gt;lastName(),\r\n        'address' =&gt; fake()-&gt;address(),\r\n    ]);\r\n    $student_item-&gt;subject()-&gt;attach([1, 2, 3]);\r\n}<\/pre>\n<p><strong>sync() function<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">pubilc function update (){\r\n    Subject::create([\r\n        ['name' =&gt; 'Drawing'],\r\n        ['name' =&gt; 'Social Science'],\r\n    ]);\r\n\r\n    $student_item = Student::find(1);\r\n    $student_item-&gt;subject()-&gt;sync([4, 5]);\r\n}<\/pre>\n<p><strong>detach() function<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">Code:\r\n\r\npubilc function destroy (){\r\n    $student_item = Student::find(1);\r\n    $student_item-&gt;subject()-&gt;detach();\r\n    $student_item-&gt;delete();\r\n}<\/pre>\n<\/li>\n<li>Retrieve Records:\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">pubilc function index (){\r\n    $student_list = Student::with('subject')-&gt;get();\r\n    return view ('student', compact('student_list'));\r\n}<\/pre>\n<p>Same way we can define a single students and assign multiple subjects to that particular student. This\u2019ll be a vice-versa process.\n<\/ol>\n<\/li>\n<\/ol>\n<\/li>\n<\/ol>\n<p>So, this way we can define Many to Many Relationships in Laravel through migration and foreign references.<\/p>\n<p>The same way we can create a common media table which will store only media file names and &#8216;id&#8217; of the other tables (users, posts, products, etc.). This will be polymorphic many to many relationships and through 2 tables only.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Many to many relationships will occur when we&#8217;ve 2 tables which are interconnected with each other with multiple records. Definition: Many-to-many (M:M) &#8211; is used to relate many records in the table A with many records in the table B. A record (&#8216;parent&#8217;) in Table A can have many matching records (&#8216;children&#8217;) in Table B, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":8483,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[10],"tags":[],"class_list":["post-7901","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-laravel"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/7901"}],"collection":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/comments?post=7901"}],"version-history":[{"count":13,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/7901\/revisions"}],"predecessor-version":[{"id":8482,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/7901\/revisions\/8482"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media\/8483"}],"wp:attachment":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media?parent=7901"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/categories?post=7901"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/tags?post=7901"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}