Skip to main content

Laravel One to Many Eloquent Relationship Tutorial

laravel one to Many eloquent relationship

Hi Dev,

In this tutorial, I Will explain you how to create laravel one to Many eloquent relationship. We will create one to many relationship in laravel. We will learn how we can create migration with foreign key schema, retrieve records, insert new records, update records etc. I will show you laravel hasMany relationship example.

We will create "employee" and "salary" table.both table are connected with each other, I will create one to many relationship with each other by using laravel Eloquent Model, We will first create database migration, then model, retrieve records and then how to create records too.One to Many Relationship use "hasMany()" and "belongsTo()" for relation.

Here, I will give you full example for laravel one to many eloquent relationship as bellow.

Step:1 Create Migration

In this example, we will need two tables in our database employee and salary.I will start to create the model and migrations, then we will define the one to hasMany relationship.To generate models and migrations, run below two commands in your terminal.


php artisan make:model Employee -m

php artisan make:model Salary -m

Above command will generate two models in your app folder called Employee and Salary. You will also find two new migrations in your database/migrations folder.

Your newly created models and migration after add table field: Path:database\migrations\2014_10_12_000000_create_employee_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateEmployeeTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('employee', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('salary_id');
$table->integer('extra_salary_id');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('employee');
}
}
Path:database\migrations\2014_10_12_000000_create_salary_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateSalaryTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('salary', function (Blueprint $table) {
$table->id();
$table->integer('amount');
$table->date('payment_date');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('salary');
}
}
Now run the below command to create employee and salary tables in your database:

php artisan migrate
Step:2 Create Model Relationship

Now in this step, we have employee and Salary tables ready, let’s define the one to manMany relationship in our models. our app/Employee.php model file and add a new function called salary() which will return a hasMany relationship like below:

app\Employee.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
/**
* Run the migrations.
*
* @return void
*/
protected $fillable = [
'name','salary_id','extra_salary_id'
];
/**
* Run the migrations.
*
* @return void
*/
public function salary()
{
return $this->belongsTo(Salary::class);
}
}

you can see, in the salary() method we are defining a hasMany relationship on Salary model.

Now we will defining Inverse One To Many Relationship in Laravel.As we have defined the hasMany relationship on Brand model which return the related records of Salary model, we can define the inverse relationship on the Salary model.Open your app/Salary.php model file and add a new method called employee() in it which will return the related brand of a Salary.

app\salary.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Salary extends Model
{
/**
* Run the migrations.
*
* @return void
*/
protected $fillable = ['amount','payment_date'];
/**
* Run the migrations.
*
* @return void
*/
public function employer()
{
return $this->hasMany(Employer::class);
}
}

As you can see, in employee() method we are returning a belongs to relation which will return the related employee of the salary.

Step 3 : Insert Records

Let’s in this step add data to employee and salary from controller:

app\Http\Controllers\Employee.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Employee;
use App\Salary;
use Hash;

class EmployeeController extends Controller
{
public function Employee()
{
$employee = employee::find(1);
$employee->name = "Test Name";
$employee->salary_id ="1"
$employee->extra_salary_id ="2"

$employee = $employee->salary()->save($employee);
}
}

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Employee;
use App\Salary;
use Hash;

class EmployeeController extends Controller
{
public function Salary()
{
$employee = employee::find(1);

$salary1 = new Salary;
$salary->amount = '123456789';
$salary->payment_date = '15/07/2020';

$salary2 = new Salary;
$salary->amount = '123456789';
$salary->payment_date = '16/07/2020';

$employee = $employee->salary()->saveMany([$salary1, $salary2]);

}
}
Step 4 : Retrieve Records

Now in this step retrieve records model

app\Http\Controllers\Employee.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Employee;
use App\Salary;
use Hash;

class EmployeeController extends Controller
{
public function index()
{
$employee = Employee::find(1);

$employee = $employee->salary;

dd($employee);

$salary = Salary::find(1);

$salary = $salary->employee;

dd($salary);
}
}
it will help you....

Comments

Popular posts from this blog

Laravel Scout Algolia Full Text Search Example

Hi Guys Today,I will tell how you can full text search utilizing scout algolia. i will show the example of laravel scout algolia full text search.you can full text search utilizing scout algolia api.it can this example full expound scout algolia full text search. I will show the rudimental step of scout algolia api full text search.if you can utilize full text search for install scout and Algolia api package.we are utilizing algolia api utilizing full text search example in laravel. Here the following steps example laravel full text search Using scout algolia Step 1: Create Laravel Project In this step create laravel project following command. composer create-project --prefer-dist laravel/blog Step 2: Database Configuration After create laravel project , we require to make database configuration, you have to add following details on your .env file. 1.Database Username 1.Database Password 1.Database Name In .env file also available host and port details, you can configu

Laravel IP Address Using Get Location Example

Hi Dev, Today,I will learn you how to get location useing ip address in laravel. we will show example of laravel ip address using get location. you can easy to get location useing ip address in laravel.In this example, I will useing stevebauman/location packege get location useing ip address in laravel. Many time you will need to get visitor's details for security, spam prevention etc. It's very easy to get visitor ip address and their location in PHP Laravel. Step 1: Install stevebauman/location Now, We will install stevebauman/location package using below command.Require this package with composer. It is recommended to only require the package for development. composer require stevebauman/location Step 2: Add providers and aliases In this step,We will add below providers and aliases in the "config/app.php" file. config/app.php 'providers' => [ .... Stevebauman\Location\LocationServiceProvider::class, ], 'aliases' => [ .... 'Loca

Laravel 6 validation required if another field is empty

Hii guys, In this artical, i will give you example of laravel 6 in validation required if another field is empty. We know laravel provide several in-built laravel 6 validation required_without . If you need to add validation rules like required if other field is empty in laravel then you can do it using required_without. I am going to explain you, If you can not enter test (field) value at that time test1 (field) is required. So at that time you can add validation required_without. So, you can use this way: "test1" =>"required_without:test" Example: public function store(Request $request) { $request->validate([ "test" =>"required", "test1" =>"required_without:test" ]); dd("Done!"); } If return validation error otherwise show Done!. It will help you...