【问题标题】:Laravel - Trying to get property 'name' of non-object (View: C:\xampp\htdocs\jairusreport\resources\views\layouts\header.blade.php)Laravel - 试图获取非对象的属性“名称”(查看:C:\xampp\htdocs\jairusreport\resources\views\layouts\header.blade.php)
【发布时间】:2019-11-16 06:53:16
【问题描述】:

我在 Laravel 5.8 上有一个应用程序。每次用户在应用程序上停留很长时间时,都会出现此错误

试图获取非对象的属性“名称”(查看:C:\xampp\htdocs\jairusreport\resources\views\layouts\header.blade.php)

几天来,我一直在与一个特定的错误作斗争,这真的浪费了我的时间。我已经完成了下面错误的截图。

身份验证/登录控制器

class LoginController extends Controller   
{
use AuthenticatesUsers;
protected $redirectTo = '/dashboard';

protected function hasTooManyLoginAttempts ($request) {
    $maxLoginAttempts = 2;
    $lockoutTime = 5; // 5 minutes
    return $this->limiter()->tooManyAttempts(
        $this->throttleKey($request), $maxLoginAttempts, $lockoutTime
    );
}  

public function __construct()
{
    $this->middleware('guest')->except('logout');
}

public function logout()
{
    $user = Auth::user();
    Log::info('User Logged Out. ', [$user]);
    Auth::logout();
    Session::flush();

    return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/login');
}    
}

问题的原因是什么。我该怎么做才能解决这个问题。

【问题讨论】:

    标签: laravel


    【解决方案1】:

    有两种可能

    1. 要么数据库中没有名称即名称的字段

    2. 或者你没有登录。

    用于检查用户是否登录

    if(Auth::check())
    {
       echo Auth::user()->id;
     }
    

    检查以上条件,别忘了在用户模型中添加这个

    class user
    {
       protected $fillable = [
        'name'
       ];
     }
    

    【讨论】:

    • Auth::user()->name 不会在users 表上没有列name 时抛出错误;它只是回显(或返回)""。问题是Auth::user() 正在返回null。第 2 点是正确的,第 1 点是错误的。
    • 1.字段(名称)存在于数据库中。 2.我登录是因为登录后显示名字
    • 好的,然后你可以查看我更新的答案。如果它工作正常,然后检查会话生命周期。
    【解决方案2】:

    Laravel 使用会话来跟踪经过身份验证的用户。会话可能超时,并且用户正在注销。

    为避免这导致您的视图出现问题,我建议对 Auth::user() 进行空检查或使用带有刀片 if 块的 Auth::check()

    如果要修改SESSION_LIFETIME,请看config/session.php

    【讨论】:

      猜你喜欢
      • 2020-09-26
      • 2020-04-16
      • 2020-05-23
      • 2018-03-22
      • 2019-02-24
      • 2019-04-08
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多