Ad

How To Join Three Table In Laravel Eloquent?

- 1 answer

I have three tables:

consignee (id,name) , jobs(id,consignee_id), expenses(id,job_id)

In my ExpensesController

public function index(){
        $expenses = \App\Expense::all();
        return view('expenses.index', compact('expenses'));}

in my index view page i want get all the details in expenses table with consignee name now in my view page

@foreach($expenses as $expense)
<tr>
  <td width="5%">{!! $expense->id !!}</td>
<td width="7%">{!! $expense->date !!}</td>
<td width="7%">{!! $expense->job_id !!}</td>
<td width="10%">{!!$expense-> !!}</td></tr>
                        @endforeach

i dont know how to get consignee name in my index view any one suggest me idea

Ad

Answer

Instead of:

$expenses = \App\Expense::all();

you can use:

$expenses = \App\Expense::select('expenses.*','consignee.name')
            ->leftJoin('jobs','jobs.id','=','expenses.job_id')
            ->leftJoin('consignee','consignee.id','=','jobs.consignee_id') 
            ->get();

This way you make join with 2 other tables and get name of Consignee.

Ad
source: stackoverflow.com
Ad