Reputation: 411
I'm trying to join two different tables to display in the foreach loop in my index.blade
file
My Controller:
public function index()
{
$users = DB::table('accounts')
->join('users', 'accounts.user_id', '=', 'users.id')
->select('users.accno', 'accounts.*')
->first();
return view('accounts.index', compact('users'));
}
My blade:
@foreach($users as $user)
<tr>
<td>{{ $user->accno }}</td>
<td>{{ $user->balance }}</td>
<td>{{ $user->amt }}</td>
</tr>
@endforeach
My index.blade.php where I'm implementing the controller, the {{user->accno}}
is from my user table and the rest is from accounts table
Upvotes: 2
Views: 156
Reputation: 361
$users = DB::table('accounts')
->join('users', 'accounts.user_id', '=', 'users.id')
->select('users.accno', 'accounts.*')
->first();
In your controller, you are using for first()
. So need to use foreach
. Just write:
<tr>
<td>{{ $user->accno }}</td>
<td>{{ $user->balance }}</td>
<td>{{ $user->amt }}</td>
</tr>
Or you should use get()
instead of first()
. But it depends on your data if you want return only one data you should use first(). If you want to return a lot of data you should use get().
Controller:
$users = DB::table('accounts')
->join('users', 'accounts.user_id', '=', 'users.id')
->select('users.accno', 'accounts.*')
->get();
Blade:
@foreach($users as $user)
<tr>
<td>{{ $user->accno }}</td>
<td>{{ $user->balance }}</td>
<td>{{ $user->amt }}</td>
</tr>
@endforeach
Upvotes: 1