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
Source: stackoverflow.com
Answered By: Anand
To use two database tables in the same view in Laravel, you need to follow these steps:
- 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 theconnections
array.
For example:
php'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',
],
],
- 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:
phpnamespace 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';
}
- In your controller, you can then retrieve data from both tables using the two models, and pass them to your view.
For example:
phpuse 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'));
}
}
- Finally, in your view, you can access the data from both tables as separate variables.
For example:
html@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.
Comments
Post a Comment