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

React Native Flexbox Tutorial With Example

Hi Dev, Today, I will learn you how to create flexbox in react native. You can easily create flexbox in react native. First i will import namespace View , after I will make flexbox using View tag in react native. Here, I will give you full example for simply display flexbox using react native as bellow. Step 1 - Create project In the first step Run the following command for create project. expo init flexbox Step 2 - App.js In this step, You will open App.js file and put the code. import React, { Component } from 'react' import { View, StyleSheet } from 'react-native' const Home = (props) => { return ( <View style = {styles.container}> <View style = {styles.redbox} /> <View style = {styles.greenbox} /> <View style = {styles.corolbox} /> <View style = {styles.purplebox} /> </View> ) } export default Home const styles = StyleSheet.create ({ container: { flexDirection:...

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...

Laravel 8 Toastr Notifications using yoeunes/toastr package Tutorial

Laravel 8 Toastr Notifications using yoeunes/toastr package Example Hi Guys Today, I will learn with you how to install and use toastr notifications using yoeunes/toastr package in laravel application.we will use yoeunes/toastr package.we will write step be step tutorial for laravel toastr notifications. Toastr notifications yoeunes/toastr package provides warning,success,error and info notifications.You have to just follow few step for implement toastr notifications in your laravel application. In this example i give you example from scratch. So just follow bellow step. Step 1: Install yoeunes/toastr package We need to install yoeunes/toastr composer package for datatable, so you can install using following command: composer require yoeunes/toastr After that you need to set providers and alias. config/app.php 'providers' => [ ... Yoeunes\Toastr\ToastrServiceProvider::class ... ]; As optional if you want to modify the default configuration, you can publish...