【问题标题】:{{ auth()->user()->email }} / {{ Auth::user()->email }} not working in x-component{{ auth()->user()->email }} / {{ Auth::user()->email }} 在 x 组件中不起作用
【发布时间】:2021-11-28 00:37:48
【问题描述】:

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

我又遇到了同样的错误。

【问题讨论】:

    标签: laravel laravel-8 laravel-blade laravel-fortify


    【解决方案1】:

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

    @auth
        <x-navbar></x-navbar>
    @endauth
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      • 2020-09-05
      • 2016-10-10
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 2023-02-04
      相关资源
      最近更新 更多