0

php artisan make:component Navbar,创建:

  • App\View\Components\Navbar.php
  • app\resources\views\components\navbar.blade.php

放置{{ auth()->user()->email }}{{ Auth::user()->email }}在刀片文件中,给出了这个错误:

  • Trying to get property 'email' of non-object.

试图通过将我的更改App\View\Components\Navbar.php为:

<?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 = 'info@example.com';
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\Contracts\View\View|\Closure|string
     */
    public function render()
    {
        return view('components.navbar');
    }
}

并添加{{ $email }}到我的刀片文件中并且它有效。

但是,我想显示来自经过身份验证的用户的电子邮件地址,所以我改为App\View\Components\Navbar.php

<?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');
    }
}

我又遇到了同样的错误。

4

1 回答 1

1

您遇到的错误是因为用户未通过身份验证。也许在调用刀片文件中的组件之前添加一个检查,将组件包装在 @auth 指令之间。像这样的东西

@auth
    <x-navbar></x-navbar>
@endauth
于 2021-10-08T01:05:26.797 回答