Laravel - How to get Data From Two Models?

10-Apr-2023

.

Admin

Hi Guys,

In this example,I will learn you how to get data from two models in laravel.you can easy and simply get data from two models in laravel.

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.

Example


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Parentuser;

use App\Models\Student;

class TestController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

$parent = Parentuser::get();

$student = Student::get();

$data = $parent->concat($student);

dd($data);

}

}

Output:

Illuminate\Database\Eloquent\Collection {#281 ?

#items: array:4 [?

0 => App\Models\Parentuser {#297 ?}

1 => App\Models\Parentuser {#298 ?}

2 => App\Models\Student {#1015 ?}

3 => App\Models\Student {#1014 ?}

]

}

Table 1:

Table 2:

It will help you...

#Laravel 8

#Laravel 7

#Laravel

#Laravel 6