Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to Create Relations in Laravel Migration

How to Create Relations in Laravel Migration?

Aman Jain, August 18, 2022March 16, 2024

Laravel relation provides almost all feature to create the database schema and one of best feature is create relations in laravel migration. As We know relations are used to create the associations between the tables and there is three types of relations in mysql which is one-to-one, one-to-many, and many-to-many. Relations consist foreign key and primary key.

In our this article i will show you to create relations between the tables in laravel migration. To create the relations we need to create the primary key and foreign key. Primary key is used to create the relation with foreign key.

In this post we will take a simple example in which we will create two tables and primary key and foreign key for relation. This example will work all version of laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9.

Let’s have simple syntax of create relation using foreign, references and on methods of laravel Schema class.

Here is the syntax

$table->foreign('user_id')->references('id')->on('users');

Here, we used foreign method which accepts name of column in child table, references to define the name of column in parent table or reference table and on to define the name of table.

We will use the php artisan command to generate the Laravel migration and php artisan migrate command to modify the table.

Let’s understand it step by step

Step 1 : Generate migration file

To generate the migration file we will use the laravel artisan command so open the terminal in project and run below command

php artisan make:migration movies_table

and another table users

php artisan make:migration create_users_table

Above command will create a migration file in folder database/migrations

Output: 
Created Migration: 2022_06_30_174050_movies_table
Created Migration: 2022_06_30_174050_create_users_table

Step 2 : Open generated migration file and update

In the last step we created a migration file using the artisan command and now we wanted to Create Relations between the tables so adding a user_id column as integer.

so let’s open the file and start editing

<?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('email')->unique();
            $table->timestamps();
        });
    }

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

and another movies table

<?php

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

class CreateMoviesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('movies', function (Blueprint $table) {
            $table->id();
            $table->string('email')->unique();
            $table->integer('user_id');
            $table->string('title');
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
    }

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

as you can see we have created string field using $table->foreign('user_id')->references('id')->on('users'); syntax and created simple users table so we can connect association between users and movies. here users is parent or reference table, movies is child or foreign table and so id is column of parent users table and user_id is child table column.

Step 3 : Run Migration

In this step we will execute our migration in database using below command

php artisan migrate

This will create table in database and the output

Output: 
Migrating: 2022_02_15_174050_movies_table
Migrated:  2022_02_15_174050_movies_table (20.08ms)
Migrating: 2022_02_15_174050_create_users_table
Migrated:  2022_02_15_174050_create_users_table (20.08ms)

Also Read : How to delete column in laravel migration ?

Related

Php Laravel Laravel 9 laravelmigrationrelation

Post navigation

Previous post
Next post

Related Posts

Php Laravel hasMany

How to Use hasMany Relationship in Laravel with Example ?

February 27, 2022November 10, 2023

Laravel hasMany relationship is used to create the relation between two tables. hasMany means create the relation one to Many. For example if a article have comments and we wanted to get all comments of the article then we can use hasMany relationship . Database Relations are used to create…

Read More

How to print database query in laravel 8 ?

January 1, 2022February 22, 2024

Sometime to debug the MySQL query in laravel eloquent we need to print the raw MySQL query. In laravel we have multiple methods to print database query in laravel 8 and we can also print the query before executing it. Laravel eloquent method to print the query The first approach…

Read More
Php Google Map with Multiple Marker and Info Box in Laravel

Google Map with Multiple Marker and Info Box in Laravel

August 30, 2022March 16, 2024

In this article we will learn to integrate google map with multiple marker and info box in laravel. Google maps are used to navigate the user location or indicate the location of business and any user. Sometimes In our application we want to show the multiple location with some information…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version