What Is One To Many Eloquent Relationship In Laravel Framework

admin_img Posted By Bajarangi soft , Posted On 08-09-2020

A one-to-many relationship is used to define relationships where a single model owns any amount of other models. One To Many relationship also known as hasMany relationship links one row in the database table to many rows in other database tables. This relationship type is mostly used while Laravel application development due to its use case.

What Is One To Many Eloquent Relationship In Laravel Framework

 One To Many Eloquent Relationship

Lets start.
How to define One To Many Eloquent Relationship


1.Create laravel project and connect to database in .env file.

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

2.Create Model and Migrate it.
To implement the one to Many relationship in Laravel, we need two models: Employee and Transactions

Now we create Employee and Transactions models in fresh project so run below commands in comand prompt.

php artisan make:model Employee -m

php artisan make:model Transaction -m


3.After Created Implement code in Model and migration files as below

Employee.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
   protected $table = 'Employees';
    protected $fillable = [
        'employee_name', 'salary', 
    ];
    
}


Transactions.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Transaction extends Model
{
   
   protected $table = 'Transactions';
    protected $fillable = [
        'employee_id', 'transaction_amount',
    ];
    
}


2020_09_04_115547_create_employees_table.php

<?php

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

class CreateEmployeesTable extends Migration
{
    public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->increments('id');
            $table->string('employee_name');
            $table->integer('salary');
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('employees');
    }
}


2020_09_04_115902_create_transactions_table.php

<?php

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

class CreateTransactionsTable extends Migration
{
    public function up()
    {
        Schema::create('transactions', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('employee_id');
            $table->integer('transaction_amount');
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('transactions');
    }
}


3.After creating new model now we need create Company controller.

php artisan make:controller CompanyController


4.Creating a One To Many Relationship in Employee and Transactions Models

Defining One To Many Relationship in Employee.php

public function transactions()
{
    return $this->hasMany('App\Transaction');
}


Defining Inverse One To Many Relationship in Transactions.php

public function employee()
{
    return $this->belongsTo('App\Employee');
}


5.Creating a One To Many Relationship Impement code in company controller to access one to many relationship.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Employee;
use App\Transaction;

class CompanyController extends Controller
{
  
    public function index()
    {
//      $data=Transaction::find(1)->employee->amount; //to get single data from Transaction model
//      $data=Employee::find(1)->transactions;//to get single data from Employee model
        $data  = Employee::with('transactions')->get(); // For multiple data
        return $data;
    }
  
}


Create Route in web.php

Route::get('employee/onetomany', 'CompanyController@onetomay')->name('employee.onetomany');


6.Filtering  a One To Many Relationship Impement code in company controller to filter one to many relationship.

$Employee = Employee::find(1);
$data = $Employee->transactions()
    ->where('transaction_amount', '>', '500')
    ->orderBy('name', 'asc')
    ->get();
return $data

7.Deleteing a One To Many Relationship Impement code in company controller to delete one to many relationship.

$Employee = Employee::find(1);
$Employee->transactions()->delete();

 

Related Post