Sunday 21 April 2019

How to Join Multiple Table in Laravel 5.8



This is one more tutorial on Laravel 5.8 framework and in this post you can find how to join multiple table in Laravel 5.8 framework. Here we will take example of fetch data from two or more table by using inner join in Laravel 5.8 and display on web page. If you are looking for learn how to make inner join with multiple table in Laravel 5.8 then this tutorial will help you because here we have take simple example for fetch data from multiple table from scratch.

Join Table means returns the records or rows which are present in both table, for this there is at least one table column match between two table. So, this type of join we have to make in Laravel 5.8 framework. There is major benefits of join of multiple table is that in one query execution you can fetch data from multiple table. Below you can find source of Laravel 5.8 join multiple table by using inner join.







JoinTableController.php


app/Http/Controllers/>JoinTableController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class JoinTableController extends Controller
{
    function index()
    {
     $data = DB::table('city')
       ->join('state', 'state.state_id', '=', 'city.state_id')
       ->join('country', 'country.country_id', '=', 'state.country_id')
       ->select('country.country_name', 'state.state_name', 'city.city_name')
       ->get();
     return view('join_table', compact('data'));
    }
}
?>


join_table.blade.php


resources/views/join_table.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - Join Multiple Table</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Laravel 5.8 - Join Multiple Table</h3>
     <br />
   <div class="table-responsive">
    <table class="table table-bordered table-striped">
           <thead>
            <tr>
                <th>Country</th>
                <th>State</th>
                <th>City</th>
            </tr>
           </thead>
           <tbody>
           @foreach($data as $row)
            <tr>
             <td>{{ $row->country_name }}</td>
             <td>{{ $row->state_name }}</td>
             <td>{{ $row->city_name }}</td>
            </tr>
           @endforeach
           </tbody>
       </table>
   </div>
  </div>
 </body>
</html>


web.php


routes/web.php

Route::get('join-table', 'JoinTableController@index');


7 comments: