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 where or condition with example

How to use laravel where or condition with example ?

January 15, 2022February 19, 2022

Laravel eloquent provides multiple ways to build the query one the of the feature of laravel eloquent is creating dynamic query based on condition or complicated queries.In this article i will show you to build where or condition in laravel with example. I will show you multiple example to create…

Read More
Laravel get single column value in laravel

How to get single column value in laravel ?

November 14, 2023March 16, 2024

In this guide, we’ll dive into get single column value in Laravel Eloquent ORM. In Laravel development, optimizing database queries is pivotal for creating efficient and high-performance applications. This technique is valuable for extracting targeted data from your database, enhancing the precision and speed of your application. To illustrate get…

Read More
Php Laravel blade for and loop varible

Laravel blade foreach, for and loop variable with example

December 18, 2021October 4, 2022

Laravel blade provides easy way to iterate a long list array or loop using @foreach and @for. @foreach and @for both used same structure as php foreach and for. In this article i will show you to use @foreach and @for loop with example and also the $loop variable. Loop…

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