Laravel One to Many Eloquent Relationship Tutorial

A one-to-many relationship in Laravel is “defined as a Single model owning multiple models.” For example, A person has infinite Mobile numbers, or a Blog Post has multiple comments. We can set the one-to-many relationships by defining the function in the model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
  /**
  * Get the comments for the blog post.
  */
  public function comments()
  {
    return $this->hasMany('App\Comment');
  }
}

In the above’s example, Blog Post has multiple comments. So we can define the function as comments, and also, we can associate it with hasMany(). Eloquent will automatically determine the proper foreign key column on the Commentmodel.

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 model Comment is post_id.

When the relationship has been defined, we can access the collection of comments by accessing the comments property.

<?php

$comments = App\Post::find(1)->comments;

foreach ($comments as $comment) {
  //
}

We will learn this relationship with the following example.

  1. Employee Model
  2. Transaction Model

An employee has multiple transactions. So we can define the relationship as One To Many. First, we will install the Laravel project and then create the two tables. Also, we will develop models and controllers and then associate the models with one another.

Step 1: Configure The Laravel.

Install Laravel by the following command.

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

Configure the database in the .env file.

Also, we will create One model, schema, and controller file inside our project.

php artisan make:controller EmployeeController

php artisan make:model Employee -m

Here, we will see that three files are created inside the project.

The migration file looks like this after defining the schema.

<?php

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

class CreateEmployeesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->increments('id');
            $table->string('employee_name');
            $table->integer('amount');
            $table->timestamps();
        });
    }

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

Run this migration by the following command.

php artisan migrate

Make a view file to enter the details of an employee. So go to the resources  >>  views, and inside that folder, create one view file called createEmployee.blade.php.

<!doctype html>
<html>
   <head>
      <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css" />
   </head>
   <body>
      <div class="container">
         <br/>
           <div class="panel panel-primary">
            <div class="panel-heading">
                 Add Employee Details
            </div>
            <div class="panel-body">
               <form method="post" action="">
                  {{csrf_field()}}
                  <div class="form-group">
                     <label class="col-md-4">Employee Name</label>
                       <input type="text" class="form-control" name="employee_name"/>
                  </div>
                  <div class="form-group">
                     <label class="col-md-4">Employee Salary</label>
                     <input type="text" class="form-control" name="employee_salary"/>
                  </div>
                  <div class="form-group">
                     <button type="submit" class="btn btn-primary">Add</button>
                  </div>
               </form>
            </div>
         </div>
      </div>
   </body>
</html>

Add the routes in the web.php file.

Route::get('employee', 'EmployeeController@create')->name('employee.create');
Route::post('employee', 'EmployeeController@store')->name('employee.store');

Update the route in the createEmployee.blade.php file’s action attribute.

<form method="post" action="{{ route('emplyee.store') }}">

Code the two EmployeeController.php functions.

<?php

namespace App\Http\Controllers;

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

class EmployeeController extends Controller
{
    public function create()
    {
    	return view('createEmployee');
    }
    public function store(Request $request)
    {
    	$employee = new Employee;
    	$employee->employee_name = $request->get('employee_name');
    	$employee->amount = $request->get('employee_salary');

    	$employee->save();

    	return 'Success';

    }
}

It will store the employee details in the database.

Step 2: Make Transaction Model And Controller.

Go to your terminal and type the following command.

php artisan make:model Transaction -m

Now, we need to define the schema for the model.

Schema::create('transactions', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('employee_id');
    $table->integer('transaction_amount');
    $table->timestamps();
});

Hit the following command.

php artisan migrate

Now, we will seed the transactions table. So go to the terminal and hit the following command.

php artisan make:seeder TransactionTableSeeder

Next, we need to write some queries to seed the database. We can also use the model factory to generate the data, but we only use the DB query builder to enter some data for now. Please ensure you have at least three Employee rows at the employee’s table.

<?php

use Illuminate\Database\Seeder;

class TransactionsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        \DB::table('transactions')->insert([
        	'employee_id' => 1,
        	'transaction_amount' => 34000,
        	'created_at' => NOW(),
        	'updated_at' => NOW()
        ]);
    	\DB::table('transactions')->insert([
        	'employee_id' => 1,
        	'transaction_amount' => 7000,
        	'created_at' => NOW(),
        	'updated_at' => NOW()
        ]);
    	\DB::table('transactions')->insert([
        	'employee_id' => 2,
        	'transaction_amount' => 92000,
        	'created_at' => NOW(),
        	'updated_at' => NOW()
        ]);
    	\DB::table('transactions')->insert([
        	'employee_id' => 2,
        	'transaction_amount' => 54000,
        	'created_at' => NOW(),
        	'updated_at' => NOW()
        ]);
        \DB::table('transactions')->insert([
        	'employee_id' => 3,
        	'transaction_amount' =>52000,
        	'created_at' => NOW(),
        	'updated_at' => NOW()
        ]);
    }
}

We need to run this file. So go to the DatabaseSeeder.php file inside the database  >>  seeds folder.

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call(TransactionsTableSeeder::class);
    }
}

We need to dump the autoload class by the following command.

composer dump-autoload

Hit the following command.

php artisan db:seed

It populates the data. Now we have two tables, and each has some data. One table is Employee, and one is Transaction.

Step 3: Define One-To-Many Relationship

In the Employee.php model, define the following function.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

Go to the terminal and hit the following command.

php artisan tinker

Tinker is the CLI tool that lets you interact with the database and act as an actual entity, and we can perform the various database operations on it.

In the tinker, you can enter the following code.

Employee::find(1)->transactions;

All the associated records of Employee with ID 1 are displayed from the model Transaction.

So this is the primary use of One-To-Many relationships.

Step 4: Inverse of Relationship.

We can define the function in the Transaction.php model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

Go to the tinker again.

Transaction::find(2)->employee->amount;

You can see the amount. So this is how we can relate to one another via Relationships in Laravel.

That’s it.

6 thoughts on “Laravel One to Many Eloquent Relationship Tutorial”

Leave a Comment

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