简体   繁体   中英

How to join two tables in Laravel

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

 $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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM