How to get data from two models in Laravel

How to get data from two models in Laravel ?

In this tutorial, I will give you an example of Get data from two models in Laravel, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.

First, what we’re doing here, This is the example :

return-array-of-collection-in-laravel
return-array-of-collection-in-laravel

Need of Concat two models in LAravel

Sometimes we have no relationship between two models and we have no foreign key to relate two models.

We have two options to Get data from different models, The first one is to use 2 foreach loops in the Blade file, and the second one is to Merge these models in the controller and get data using only a single variable.

In this article, we simply concat Two different Models and get all the data of both Models, It Will Returns an array of Collections.

Generating Migration :

Let’s create migration for Two tables using the artisan command in our Terminal.

php artisan make:migration create_test_table_1_table
php artisan make:migration create_test_table_2_table

Migration Structure :

Now we have Two migration files test_table_1 and test_table_2.

<?php

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

class CreateTestTable1Table extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('test_table_1', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('address');
        });
    }

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

<?php

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

class CreateTestTable2Table extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('test_table_2', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('address');
        });
    }

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

Run Migration :

php artisan:migrate
merge-two-models-in-laravel
merge-two-models-in-laravel

Create Model :

Now we create Two Models for different Tables.

php artisan make:model Model/TestTable1
php artisan make:model Model/TestTable2

App\Model\TestTable1

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class TestTable1 extends Model
{
    protected $table = 'test_table_1';
}

App\Model\TestTable2

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class TestTable2 extends Model
{
    protected $table = 'test_table_2';
}

Insert Dummy Data using Seeder :

If you have already Data in both Tables, So this is good for you, Otherwise, we store some Dummy Data using Database Seeder in these Tables.

Recommended Article :

Quickly Generate Data using Faker and Tinker

database\seeds\DatabaseSeeder

<?php

use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
use Illuminate\Support\Facades\DB;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
    	$faker = Faker::create();
    	foreach(range(1,5) as $index)
    	{
    		DB::table('test_table_1')->insert([
    			'name' => $faker->text(10),
                'email' => $faker->unique()->email(10),
    			'address'  => $faker->text(40),

    		]);
            DB::table('test_table_2')->insert([
                'name' => $faker->text(10),
                'email' => $faker->unique()->email(10),
                'address'  => $faker->text(40),
            ]);
    	}

        
        // $this->call(UsersTableSeeder::class);
    }
}

Run Seeder :

php artisan db:seed

Now we have 5-5 Entries in Both Tables.

Get-data-with-two-models-in-Laravel
Get-data-with-two-models-in-Laravel

Create Controller :

php artisan make:controller TestController

Create Routes :

routes\web.php

#Example of Collection Array Merge
Route::get('get-data','TestController@index')->name('get.data');

App\Http\Controllers\TestController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Model\TestTable1;
use App\Model\TestTable2;

class TestController extends Controller
{

    public function index(){
    
    $Table1_Data = TestTable1::get();
    $Table2_Data = TestTable2::get(); 
    $data = $Table1_Data->concat($Table2_Data); //Return array of Collections
    dd($data);
    }
}

Run The Application :

Run your Laravel application in your Terminal.

 http://127.0.0.1:8000/get-data

You can see the output in the given below images, We have data of Test Table1 and Test Table2 Models.

How to get data from two models in Laravel
How to get data from two models in Laravel

In this article, we learned How to get data from two models in Laravel, I hope this article will help you with your Laravel application Project.

Also Read : Save Multiple Columns Data into Single Column in Laravel

7 thoughts on “How to get data from two models in Laravel ?”

  1. Let me ask a que related to this,

    Table1 in database
    id….roll_no….fee_type….amount
    1…….12………….Tution fee….10000
    2……15…………..Exam fee….5000
    3…….12…………..Exam fee….5000

    report for user on front end

    S.N……Roll No…Tution….Exam fee
    1…………..12…………. 10000…..5000
    2…………..15…………..NULL…..5000

    Total
    15000
    5000

    how to do this, pls guide?

    1. Controller :

       public function studentdataList()
         {

          $data = StudentDetail::get();
          foreach ($data as $key => $value) {
              $collection[$value->roll_no][‘roll_no’] = $value->roll_no;
              $collection[$value->roll_no][$value->fee_type] = $value->amount;
         }
        return view(‘studentdetails’,compact(‘collection’));
      }

      Blade file :

      <body>
          <div class=“container”>
             <h3>Student Data</h3>
             <table class=“table”>
                <thead>
                   <tr>
                      <th>S.no</th>
                      <th>Roll No</th>
                      <th>Exam Fee</th>
                      <th>Tution Fee</th>
                      <th>Total</th>
                   </tr>
                </thead>
                <tbody>
                  @php $sno = 1@endphp
                   @foreach($collection as $key => $data)
                   <tr>
                      <td>{{ $sno++ }}</td>
                      <td>{{ $data[‘roll_no’}}</td>
                      <td>{{ isset($data[‘Exam’]) ? $data[‘Exam’] :  ‘NULL’ }} </td>
                      <td>{{ isset($data[‘Tution’]) ? $data[‘Tution’] : ‘NULL’ }} </td>
                      <td>{{ ( isset($data[‘Tution’]) ? $data[‘Tution’] : 0 ) + ( isset($data[‘Exam’]) ? $data[‘Exam’] : 0 ) }} </td>
                   </tr>
                   @endforeach
                </tbody>
             </table>
          </div>
       </body>

      1. Note : Hello Shubham, I think you are looking for a relationship in laravel, If you used Eloquent, all of this becomes very easy.

        you can create a stu_id field in the student_details table, and save the primary id of the students table in the students_detials table as stu_id and you can get all the student data according to the stu_id using belongTo relationship.

        follow this : Laravel Relationships.

Comments are closed.