Devnoob Devnoob - 2 years ago 98
MySQL Question

How to get data from related tables in laravel 5?

I have a search form on my page that searches through several tables, how do i do the below and search correctly? I want to be able to search the agency name, client name and type name along with username and password:

my view looks like below

@foreach ($accounts as $account)
<td> {{$account->client->name}} </td>
<td> {{$account->agency->name}} </td>
<td> {{$account->type->name}} </td>
<td> {{$account->username}} </td>
<td> {{$account->password}} </td>
<td><a href="{{route('accounts.edit',$account->id)}}"><span class="fa fa-edit"></span></a></td>

Username and password searches correctly but the joins dont bring any results

public function index(){

$search = \Request::get('search');

$accounts =
->Join('types', '', '=', 'accounts.type_id')
->Join('agencies', '', '=', 'accounts.agency_id')
->Join('clients', '', '=', 'accounts.client_id')

return view('accounts',compact('accounts'));

This worked:

->Join('types', 'accounts.type_id', '=', '')
->Join('agencies', 'accounts.agency_id', '=', '')
->Join('clients', 'accounts.client_id', '=', '')

Answer Source

Your join seems to be wrong

->Join('types', '', '=', 'accounts.type_id')
->Join('agencies', '', '=', 'accounts.agency_id')
->Join('clients', '', '=', 'accounts.client_id')

see how on both side of '=' you using accounts table you need to have one side to have types/agencies/clients for join to work.

So it would be something like

->Join('types', '', '=', 'types.type_id')
->Join('agencies', '', '=', 'agencies.agency_id')
->Join('clients', '', '=', 'clients.client_id')

saying that would need your db structure to pin point why you not getting result from join query search.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download