php artisan make:component Navbar
, created:
App\View\Components\Navbar.php
app\resources\views\components\navbar.blade.php
Placing {{ auth()->user()->email }}
or {{ Auth::user()->email }}
in the blade file, gave this error:
Trying to get property 'email' of non-object
.
Tried to fix this by changing my App\View\Components\Navbar.php
to:
<?php
namespace App\View\Components;
use Illuminate\View\Component;
class Navbar extends Component
{
public $email;
/**
* Create a new component instance.
*
* @return void
*/
public function __construct($email = null)
{
$this->email = '[email protected]';
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\Contracts\View\View|\Closure|string
*/
public function render()
{
return view('components.navbar');
}
}
And added {{ $email }}
to my blade file and it worked.
However, I want to display the e-mail address from the authenticated user, so I changed App\View\Components\Navbar.php
to:
<?php
namespace App\View\Components;
use Illuminate\View\Component;
use Illuminate\Support\Facades\Auth;
class Navbar extends Component
{
public $email;
/**
* Create a new component instance.
*
* @return void
*/
public function __construct($email = null)
{
$this->email = Auth::user()->email;
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\Contracts\View\View|\Closure|string
*/
public function render()
{
return view('components.navbar');
}
}
And I got the same error again.
CodePudding user response:
The error you're having because the user is not authenticated. Maybe add a check before calling the component in the blade file, wrap the component between @auth directive. Something like this
@auth
<x-navbar></x-navbar>
@endauth