Laravel, How to use two database tables in the same view

✔ Recommended Answer

Here it looks like there are 2 variables that are most important...

User and Menus;

I looks like the User details is of the logged in User and not of any other user then u can change it to

$user = Auth::user();$menus = $menus = Auth::user()->menus()->get();return view('menus.index', compact('menus', 'user'));

pass the whole object to the view...

if you would want to debug what values are being sent to view in user and menus

return [    'user' => $user,    'menus' => $menus,];

Now in view you can directly use the user object

{{ $user->name }} // Print User name


Answered By: Anand

Method #2

To use two database tables in the same view in Laravel, you need to follow these steps:

  1. First, you need to define two separate database connections in your Laravel application's configuration. You can do this by editing the config/database.php file and adding two separate entries under the connections array.

For example:

'connections' => [ 'mysql' => [ // your default connection details here ], 'second_db' => [ 'driver' => 'mysql', 'host' => 'second_db_host', 'port' => '3306', 'database' => 'second_db_name', 'username' => 'second_db_user', 'password' => 'second_db_password', ], ],
  1. Next, you need to create two separate models, one for each database table, and specify the corresponding connection in each model's $connection property.

For example:

namespace App\Models; use Illuminate\Database\Eloquent\Model; class FirstTable extends Model { protected $connection = 'mysql'; protected $table = 'first_table'; } class SecondTable extends Model { protected $connection = 'second_db'; protected $table = 'second_table'; }
  1. In your controller, you can then retrieve data from both tables using the two models, and pass them to your view.

For example:

use App\Models\FirstTable; use App\Models\SecondTable; class MyController extends Controller { public function myAction() { $firstTableData = FirstTable::all(); $secondTableData = SecondTable::all(); return view('my_view', compact('firstTableData', 'secondTableData')); } }
  1. Finally, in your view, you can access the data from both tables as separate variables.

For example:

@foreach($firstTableData as $firstRow) <!-- output first table data here --> @endforeach @foreach($secondTableData as $secondRow) <!-- output second table data here --> @endforeach

Note that you can also use database joins to combine data from multiple tables into a single query result, if that is more appropriate for your use case.


Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755