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 multiple where condition in eloquent

How to use laravel multiple where condition with example ?

March 5, 2022November 8, 2023

In this article i will show you to use laravel multiple where condition in eloquent. In laravel we can create multiple where condition in several ways like using the array of array, associative column and value and using multiple where clause. Sometimes we wanted to use multiple and condition or…

Read More
Php How to Create Zip of File or Folder in Laravel

How to Create Zip of File or Nested Folder in Laravel ?

May 22, 2022May 24, 2022

Zip files are used to create lossless data compression and store multiple files folder in single file. In laravel create zip of file or nested folder laravel can be archived by ZipArchive library,its gives easy to use flexibilities to developers so they can easily integrate the Zip creation activity in…

Read More

How to enable cors in web api php or laravel?

August 27, 2021August 20, 2022

Cross-Origin Resource Sharing (CORS) is mechanism which allow browser to share the resources between the other domain or port. if the cors is disabled in api or server then other domain can’t access the apis and resource of server. Example: if a server A wants to access the apis of server…

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

  • 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

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version