I am having difficulty in understanding how to pass data to a .blade
. I want to pass the users’ username ($user)
to a dashboard component. Here’s a few things I’ve tried:
return view('livewire.dashboard', ['user'=>'$user']);
return view('livewire.dashboard', compact('$user'));
return view('livewire.dashboard'->with('user',$user));
But then I realized that the class I was trying to pass the user info from didn’t know what the user variable is. Here is the class (Dashboard.php):
<?php
namespace AppHttpLivewire;
use IlluminateContractsViewView;
use IlluminateContractsViewFactory;
use IlluminateContractsContainerBindingResolutionException;
use LivewireComponent;
class Dashboard extends Component
{
/**
* @return View|Factory
* @throws BindingResolutionException
*/
public function render()
{
return view('livewire.dashboard');
}
}
And here is my web.php file:
use AppHttpLivewireDashboard;
use AppHttpLivewireUser;
// Dashboard
Route::get('/', Dashboard::class)->name('dashboard');
// I have also tried something like 'Route get user' here, also didn't work
// User routes
Route::prefix('/users')->group(function () {
Route::get('/', UserIndex::class)->name('users.index');
Route::get('/create', UserCreate::class)->name('users.create');
Route::get('/{user}', UserEdit::class)->name('users.edit');
});
I’m having difficulty understanding how components/classes/blade tamplates communicate with each other. How can I pass the username of the person currently logged in to my dashboard.blade.php file? It looks like this:
@isset($user)
Hallo {{ $user->name }},
@endisset
</div>
<div>Willkommen im Formular-Editor!</div>
<div>Neue Formulare kannst du über den Tab "Editor" oben in der Leiste anlegen. Hier kannst Du auch bestehende Formulare bearbeiten.</div>
An explanation as well as a solution would be appreciated, as I really don’t understand how Laravel works. Thank you
3
Answers
You can pass them
In Laravel Way
Read More Official LiveWire Doc
Apart from all
Laravel is a Well designed Framework. So passing the logged-in users here and there(fetch in the controller and pass to view with
$user
), you can directly access using theauth()
helper.In view
As you are using Livewire, you probably want to take advantage of data binding (one of the benifits of Livewire).
What you can do is define a
$user
property on yourDashboard
component that you can then access in thedashboard.blade.php
view.Your
Dashboard
component might look as follows (I’ve omitted code for brevity)Then in your view you would simply access
$user
In a more simpler way, you can use compact as you are using in second step. The only change you need to remove $ from user variable.
eg.