• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
Tutsplanet

Tutsplanet

Free Technical and Blogging Resources

  • Home
  • Web Hosting
  • Programming
  • Plugins
  • Twitter Trends
  • Tools
  • About Us

Programming TagsLaravel

How to Add Foreign Key in Laravel Migration?

Aug 10, 2021 Editorial Staff

Share
Tweet
Share
1 Shares

Today’s tutorial shows how to add a foreign key to a MySql table field in Laravel migration. I am sure you are in the right place to start with the migration and foreign key constraints in Laravel.
As we discussed earlier, the foremost purpose of the foreign key is to provide referential integrity between parent and child tables. By creating a foreign key you are enforcing a relationship between the tables. For example, you have two tables of users and addresses. So you cannot fill user_id in the address table that is not in the user table.

In this article, I will show you how to create a migration and add the foreign key constraints properly with two methods.

Method #1

Generate Migration Command

php artisan make:migration create_products_table

Open the generated file in the folder database/migrations, and the latest file in the folder which will hold the last part of the command in the filename.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });

        Schema::create('products_images', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('product_id');
            $table->string('image');
            $table->timestamps();

            $table->foreign('product_id')->references('id')->on('products');

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
        Schema::dropIfExists('products_images');
    }
}

Run the below command to create the database table

php artisan migrate

If you check your database admin, you will see the new table created with the given field names.

Method #2

Modify the part where we added the migration statement for products_images table.

Like below

Schema::create('products_images', function (Blueprint $table) {
    $table->id();
    $table->foreignId('product_id')->constrained();
    $table->string('image');
    $table->timestamps();
});

Run php artisan migrate and you will see the same results as Method #1

Hope you had good time with this article, please share with your friends


Editorial Staff

Editorial Staff at Tutsplanet is a dedicated team to write various tutorials about subjects like Programming, Technology and Operating Systems.

View all posts by Editorial Staff

Primary Sidebar

Quick Links

  • Top 21 Website Ideas To Make Money Online in 2021
  • A Simple YouTube Video Downloader Script in PHP
  • The 50 Most Useful jQuery Plugins for Frontend Development
  • Replace “\n” with new line characters, using Notepad++
  • Using Third-Party Libraries in Codeigniter
  • Upload Multiple Images and Store in Database using PHP and MySQL.
  • Hierarchical Tree view Category Example in Laravel
  • Laravel Image Intervention Tutorial With Example
  • How to import sql file in MySQL database using PHP?
  • Free VAT Calculator Online

Subscribe

* indicates required



Search Here

Share

   



Hot topics

  • Replace “\n” with new line characters, using Notepad++ 15 views
  • Solution: windows photo viewer opens each time save a pic file 12 views
  • A Simple YouTube Video Downloader Script in PHP 10 views
  • All Countries SQL file with Country Codes to Download 8 views
  • How to create and download a Zip file with PHP 8 views
  • Simple PHP Shopping Cart 8 views
  • How to Create PDF File From HTML Form Using Fpdf? 8 views
  • How to set up GitHub SSH in Ubuntu with example 7 views
  • How to enter new line in Microsoft Teams? 7 views
  • Open a URL in a new tab using JavaScript 7 views

Categories

  • Design & Development
  • Drupal
  • Facebook
  • General
  • How To
  • ios
  • Javascript
  • Linux
  • Magento
  • Marketing
  • News
  • PHP
  • Plugins
  • Programming
  • Snippets List
  • Social Media
  • Softwares
  • Themes
  • Tips
  • Wordpress
  • YouTube























Copyright © 2023 · Planet on Genesis Framework · Powered By BunnyCDN . Network wallpapernoon.com