代码之家  ›  专栏  ›  技术社区  ›  Wouter Dorgelo voy

{{auth()->user()->email}/{{auth::user()->email}未在x组件中工作

  •  0
  • Wouter Dorgelo voy  · 技术社区  · 3 年前

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

    1 回复  |  直到 3 年前
        1
  •  1
  •   Koussay    3 年前

    由于用户未经身份验证而导致的错误。可能在调用刀片文件中的组件之前添加一个检查,将组件包装在@auth指令之间。像这样的

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