---
description: >-
  https://www.itsolutionstuff.com/post/laravel-eloquent-relationships-tutorial-from-scratchexample.html
---

# Laravel Eloquent Relationships Tutorial From Scratch (ok)

Đọc thêm: [https://c-i-ph-n-m-m-tr-n-ubuntu-c-n-thi.gitbook.io/learn-lavarel/sau-khi-gap-cac-loi-phat-sinh-migration-gio-chung-ta-co-ban-full-ok](https://c-i-ph-n-m-m-tr-n-ubuntu-c-n-thi.gitbook.io/learn-lavarel/sau-khi-gap-cac-loi-phat-sinh-migration-gio-chung-ta-co-ban-full-ok)

## Ví dụ 1: làm dữ liệu thêm foreign (ok)

Một điều đặc biệt chú ý là khi tạo khóa phụ thì bảng phục phải được sinh ra trước \
Giải pháp 👍ta thay đổi thời gian ở tên file ví dụ:

```
2022_05_10_163257_create_countries_table.php thay đổi thành 2020_05_10_163257_create_countries_table.php
```

![](https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2FHfLlZfsWpbg5CSLcxRQd%2FScreenshot_2.png?alt=media\&token=fe34a20c-263f-4978-9f29-9fbf31b1fba5)

Sau khi gặp các lỗi đã thực hành giờ đây chúng ta có thể đưa ra bản hoàn thiện :thumbsup:)

## Ví dụ 2: làm dữ liệu thêm foreign (ok)

Chú ý: Cách này tạo ra nhiều lỗi khi migrate 😒

![](https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2FHiyQEtRk1nqFIL53egDJ%2FScreenshot_1.png?alt=media\&token=fa3d6a2f-4c56-455f-ace5-2e0da61ac8fc)

C:\xampp\htdocs\test\database\migrations\2014\_10\_12\_000000\_create\_users\_table.php

```
<?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->bigIncrements('id'); // Mặc định cái này là bigteger không âm do đó để không bị lỗi khóa phục cũng phải cùng loại :)
      $table->string('name');
      $table->string('email')->unique();
      $table->timestamp('email_verified_at')->nullable();
      $table->string('password');
      $table->rememberToken();
      $table->timestamps();
      $table->bigInteger('country_id')->unsigned();
      $table->foreign('country_id')->references('id')->on('users')->onDelete('cascade');
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('users');
  }
}
```

C:\xampp\htdocs\test\database\migrations\2022\_05\_10\_163257\_create\_countries\_table.php

```
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCountriesTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('countries', function (Blueprint $table) {
      $table->bigIncrements('id');
      $table->string('name');
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('countries');
  }
}
```

C:\xampp\htdocs\test\database\migrations\2022\_05\_10\_163113\_create\_posts\_table.php

```
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('posts', function (Blueprint $table) {
      $table->bigIncrements('id');
      $table->string("name");
      $table->bigInteger('user_id')->unsigned();
      $table->timestamps();
      $table->foreign('user_id')->references('id')->on('posts')->onDelete('cascade');
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('posts');
  }
}
```

## Laravel Eloquent Relationships Tutorial From Scratch

By Hardik Savani July 7, 2018 Category : PHP Laravel PlayUnmuteLoaded: 1.15%Fullscreen![VDO.AI](https://a.vdo.ai/core/assets/img/logo.svg)ORM stands for Object-relational mapping. Laravel introduce ORM from Laravel 5 framework and laravel 6, laravel 7, laravel 8 and laravel 9 version. We used and see the foreign key for database relationship. but in this relation laravel created relationships between model.

As we know database table is almost related to another database table. but when you are working on retrieve data, create data or etc task. you have to use a join or something on every SQL query. So it takes time and also we have to write lots of database query. But in laravel Eloquent Model Relationship we can easily make in relation by using their types.

![](https://www.itsolutionstuff.com/upload/laravel-model-relationships.png)

Why we should use laravel model relationship, So I want to give one example for this. If you have a "users" table and also you have "user\_addresses" table. both tables are connected with each other using a foreign key. There are several records in users table and also more records in your address table. If you didn't use laravel eloquent relationship then you can get all address using "join" like as below:

**Basic Model Query:**

```
$userAddresses = User::select("users.*", "user_addresses.*")                 ->join("user_addresses", "user_addresses.id_user", "=", "users.id")                 ->where("users.id", 1)                 ->get(); dd($userAddresses);
```

As you can above laravel query, you have to write long query, right now it is not big, but when you have more tables connected with users table then it can be more complected, so if we use laravel Relationship then you can do it just simple and you don't require to write every time join and anything, laravel will manage it. So you can write this way:

**Model Query Using Relationship:**

Read Also: [Laravel One to One Eloquent Relationship Tutorial](https://www.itsolutionstuff.com/post/laravel-one-to-one-eloquent-relationship-tutorialexample.html)

```
$userAddresses = User::find(1); dd($userAddresses->address);
```

As you can see how it is simple, so i can say, we have to use laravel relationship.

In this tutorial, i will explain every types with how to insert data with relation model and how to get records from database table using model. i will also give example with table migration, model, retrieve and create new records. You have to just read and you will understand how it is working on all types of relationships in laravel. You can easily use order by, filter, where condition, delete, create, update, group by, get all, get count, save etc laravel methods.

Now as bellow i listed all laravel model relationships types and you can click on it and read in details of each types.

\


\


\*\*\* Click On it and Read in Details of RelationShip types:
