Laravel 6 – ONE TO MANY Eloquent Relationship With Example

one-to-many-relationship

In this tutorial, i will discuss about one to many eloquent relationship with example.

Lets start with simple example,  Suppose you need to write code in which you have to retrieve all the cars own by related companies. You have two tables, i.e. companies and cars. The cars table is connected with company table using company_id. So how can you retrieve cars by company_id?

To accomplish our above goal, First retrieve all companies data by query on companies table and make a foreach loop. Inside foreach loop we can make another query on cars table using company_id and get cars data. This process is little time consuming and require more code.

But what if i say i have better solution to retrieve above results in efficient way using one to many eloquent relationship of laravel. Yes read below. 😉

Lets compare relationship words with our real example:

One(Company) To Many(Cars)

Lets start step by step one to many eloquent relationship tutorial.

First install fresh laravel using below command. If you have laravel installed then you can skip this part.

composer create-project --prefer-dist laravel/laravel one-to-many

Now update database credentials in .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=one-to-many
DB_USERNAME=root
DB_PASSWORD=

Now run default migrations using below command. In default migration, Laravel comes with user migration and model. You can check them under database/migrations directory. While running php artisan migrate command laravel creates database tables from migrations.

php artisan migrate

You have successfully installed laravel and you can check it by enabling server using below command.

php artisan serve

Now navigate http://127.0.0.1:8000 in your browser. You will see laravel welcome page.

Related:  Form Data Validation Using Form Requests In Laravel 6 - Part 2

Now, To make one to many relationship between company and cars table we need to create company and car models.

Create Company Model And Migrations

Lets create company model and migration using below artisan command. This command will generate company model under app/ directory and TIMESTAMP_create_companies_table.php under database/migrations directory.

php artisan make:model Company -m

Lets open company migration file and add some company info related fields.

TIMESTAMP_create_companies_table.php

<?php

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

class CreateCompaniesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('companies', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('company_name');
            // You can add more fields about company if require
            $table->timestamps();
        });
    }

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

Also modify Company.php model as shown below.

Company.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Company extends Model
{
    protected $fillable = [
        'company_name'
    ];
}

The fillable property specifies which attributes should be mass-assignable. This can be set at the class or instance level. You can get more info about $fillable property and mass-assignable here.

Don’t forget to run php artisan migrate command to create companies table in database.

Create Car Model And Migrations

Lets create car model and migrations using below command.

php artisan make:model Car -m

Open car migrations and add some car info related fields. Also include company_id fields to make relationship with company model.

TIMESTAMP_create_cars_table.php

<?php

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

class CreateCarsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cars', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('model');
            $table->float('price', 10, 2);
            $table->unsignedBigInteger('company_id');
            // You can add more fields about car if require
            $table->timestamps();
        });
    }

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

Also update car model as shown below.

Related:  Install Laravel 5.8 On Windows XAMPP Using Composer

Car.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
    protected $fillable = [
        'model', 'price', 'company_id'
    ];
}

Also run php artisan migrate command to create cars table in database.

Define One To Many Relationship

Now its time to define one to many relationship between company and car model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Company extends Model
{
    // -- OTHER CODE

    /**
     * Get the cars for the blog post.
     */
    public function cars()
    {
        return $this->hasMany('App\Car');
    }
}

The hasMany method define relationship between company and car eloquent model. Remember, Eloquent will automatically determine the proper foreign key column on the Car model. By convention, Eloquent will take the “snake case” name of the owning model and suffix it with _id. So, for this example, Eloquent will assume the foreign key on the Car model is company_id.

Suppose, if you are not following above convention method to define foreign key relationship between two models then you need to define foreign_key  and local_key in hasMany method like this:

return $this->hasMany('App\Comment', 'foreign_key', 'local_key');

In this example, we have company_id (Inside cars table) is foreign key and id (Inside companies table) is local key.

Retrieve Relationship Data

Its very easy to retrieve relationship data. We can get cars data by company like this:

$cars = Company::find(1)->cars;  // For single company

$cars  = Company::with('cars')->get(); // For multiple companies

Define Inverse Relationship

We can also get company info by car with inverse relationship. Lets define inverse relationship in car model like this:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
    // -- OTHER CODE

    /**
     * Get the company that owns the cars.
     */
    public function company()
    {
        return $this->belongsTo('App\Company');
    }
}

The belongsTo method is used to define inverse relationship between car and company eloquent model. Again remember that eloquent will find out foreign_key and local_key based on model name if you have followed conventional method. Somehow, if you override it then you need to pass all three arguments into belongsTo method like this.

return $this->hasOne('App\Phone', 'foreign_key', 'local_key');

In this example, foreign_key is company_id (In cars table) and local_key is id (In companies table). Make sure that local_key if primary_key.

Retrieve Inverse Relationship Data

Lets get company data by car model like this.

$company = Car::find(id)->company;  // For single data

$companies = Car::with('company')->get(); // For multiple data

Final Words 🙂

I hope that you may like this one to many eloquent relationship tutorial, Please share with your friends and circles. Let me know your views in the comment box. Thank you very much 🙂

About Chintan Panchal

I am web developer having 6+ year of experience of web development. Currently working on laravel and have worked on codeigniter, cakephp, symfony. Thank you :)

View all posts by Chintan Panchal →

One Comment on “Laravel 6 – ONE TO MANY Eloquent Relationship With Example”

  1. …Please, I need your help regarding this one to many relationship. I am currently Working on a project and I can’t seem to work around it. How can I chat with you directly. Thank you

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.