Laravel - How to get Data From Two Models?
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...
- How to Notifications With database Driver in Laravel 11?
- How to Send Email Via Notification in Laravel 11?
- How to Install and Configure Laravel 11 Debugbar?
- How to Like Dislike System in Laravel 11?
- How to Paginate a Model with Relationship in Laravel 11?
- Laravel 11 Upload Files to Amazon S3 Example
- Laravel 11 Send WhatsApp Messages Example
- Laravel 11 Rest API Authentication Using JWT Tutorial