AppDividend
Latest Code Tutorials

Laravel One To Many Relationship Tutorial

13,919

Get real time updates directly on you device, subscribe now.

Laravel One To Many Relationship Tutorial is today’s leading topic. A one-to-many relationship defines as a Single model owns 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. You can go through this link Laravel One To One Eloquent Relationships to understand Relationships.

<?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 above’s example, Blog Post has multiple comments. So we can define the function as comments and also, we can associate 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) {
    //
}

Laravel One To Many Relationship With Example.

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 we will create the two tables. Also, we will develop models and controllers and then associate the models between one another.

Step 1: Configure The Laravel.

Install the Laravel by the following command.

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

Now, 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 total three files are created inside the project.

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');
    }
}

Now, run this migration by the following command.

php artisan migrate

Make a view file to enter the details of an employee. So go 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>

Now, add the routes in the web.php file.

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

Also, update the route in the createEmployee.blade.php file’s action attribute.

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

Now, code the two EmployeeController.php function.

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

Related Posts
1 of 39
php artisan make:seeder TransactionTableSeeder

Okay, next thing is we need to write some queries to seed the database. We can also use the model factory to generate the data, but for now, we only use the DB query builder to enter some data. Please make sure; you have at least three Employee rows in 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);
    }
}

Also, we need to dump the autoload class by the following command.

composer dump-autoload

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

Now, 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');
    }
}

Now 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 can act as an actual entity, and we can perform the various database operation on it.

In the tinker, you can enter the following code.

Employee::find(1)->transactions;

You can see all the associated records of Employee with the ID 1 is displaying from the model Transaction.

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

Step 4: Inverse of Relationship.

Similarly, 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 one another via Relationship in Laravel.

Finally, Our Laravel One To Many Relationships Tutorial is over. Thanks for Reading.

3 Comments
  1. Gabriel says

    Awesome tutorial. Thanks!

  2. Jaikangam Malangmei says

    how to insert data into transactions table without using thinker. ?

    1. fredd says

      public function Transaction(){
      return $this->hasMany(Customer::class, ‘user_id’); //a mucho
      }

Leave A Reply

Your email address will not be published.

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