Laravel 8 One to Many Eloquent Relationship Tutorial

Laravel 8 One to Many Eloquent Relationship Tutorial

Hello friends, Today i will explain Laravel 8 One to Many Eloquent Relationship example. One to Many relationship will use when one table associated with multiple tables. Laravel 8 one to many relationship use when single model is the parent to one or more child models. For example, blog post may have more than one comments.

In this tutorial i will discuss about Laravel 8 eloquent relationships example from scratch. There are many relationship in Laravel. Today i will discuss on One to Many Eloquent Relationship. So let’s following my step to learn one to many eloquent relationship.

Has Many Eloquent Relationship Example

Like the hasOne method, you may also override the foreign and local keys by passing additional arguments to the hasMany method.

Step 1 : Create-Project

In this step we will create new laravel project. So let’s run this command to download a fresh laravel app.

composer create-project --prefer-dist laravel/laravel eloquent

Step 2 : Create Migration and Model

We required two table for hasmany eloquent relationship example. One customer and other is compnay . so run two below commands to create migration:

php artisan make:model Company -m
php artisan make:model Customer -m

Company table

public function up()
{
    Schema::create('companies', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
    });
}

customer table

public function up()
{
    Schema::create('customers', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('email');
        $table->integer('company_id');
        $table->timestamps();
        $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
    });
}

Now run following command to migrate those table into our database.

php artisan migrate

Now time to setup our relationship between company and customer. Se mind that one company might have many customer. So go to your company model and paste the below code.

Company Model 

namespace App;
use Illuminate\Database\Eloquent\Model;
 
class Company extends Model
{
    public function customers(){
   	return $this->hasMany(Customer::class);
   }
 
}

Customer Model

namespace App;
use Illuminate\Database\Eloquent\Model;
 
class Customer extends Model
{
    public function company()
    {
    	return $this->belongsTo(Company::class);
    }
}

Step 3 : Create Controller

Now we have to create our controller. To create controller , run following command

php artisan make:controller EloquentController

app/Http/Controllers/EloquentController.php

namespace App\Http\Controllers;

use App\Company;
use App\Customer;
use Illuminate\Http\Request;
class EloquentController extends Controller
{
    public function Home()
    {
    	$companies = Company::all();
        return view('welcome',compact('companies'));
    }
}

Step 4: Create Route

Route::get('/','EloquentController@Home');
Step 5 : Setup Blade file
Now for showing our relational data from database, Just paste the following code to welcome.blade.php.
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Eloquent</title>

    </head>
    <body>
        
     @foreach($companies as $company)

         <h3>{{ $company->name }}</h3>
                        
             <ul>
                 @foreach($company->customers as $customer)
                    <li> {{ $customer->name }}</li>
                  @endforeach
             </ul> 
     @endforeach

    </body>
</html>

I hope you understand of one to many relationship and it can help you…

Read Also :  Laravel 7 Socialite Login with Google Account Example