【问题标题】:Error Trying to get Property of non object (laravel 5.3)尝试获取非对象的属性时出错(laravel 5.3)
【发布时间】:2017-01-10 16:46:54
【问题描述】:

我正在尝试访问 AppserviceProvider 中经过身份验证的用户 ID,当我在应用程序中时它工作正常意味着一旦登录后它工作正常,但是当我注销时它给出错误并且不转到登录页面

试图获取非对象的属性

这是我用boot方法编写的Appserviceprovider代码。

public function boot()
{
    view()->composer('*', function($view){
    $view->with('user', Auth::user());

    $counter = DB::table('notifications')->where('notifications.userid', Auth::user()->id)->count();
    View::share('counter', $counter);
    });

当我注销时,它在上述查询的 where 子句中出现错误。这是因为注销后无法获取身份验证用户ID .. 请帮助我如何修复它或如何以最好的方式完成它(如果有的话)

【问题讨论】:

  • 问题是这个Auth::user()->id注销时Auth::user()是空的

标签: php laravel


【解决方案1】:

你应该看看这个Laravel protecting routes

您可以保护路线,以便在您未登录时无法访问它们。这应该可以解决您的问题。

如果您希望在未登录时可以访问此路由,则应在查询周围添加 if 语句。可以使用Auth::check()查看用户是否登录。

if(Auth::check()) {
    //Do stuff
}

【讨论】:

    【解决方案2】:

    为了避免当您因为Auth::user() 为空而退出时,请使用三元条件

    如果Auth::user() 则使用Auth::user()->id 否则如果不使用null 值代替

    Auth::user() ? Auth::user()->id : null
    

    改变这一行

    $counter = DB::table('notifications')->where('user_notifications.user_id', Auth::user() ? Auth::user()->id : null)->count();
    

    【讨论】:

    • @recoverymen 你能var_dump(Auth::user()); 看看你退出后的结果吗
    • 但是当你注销时它是否为空?
    • 所以它是空的你真的用过这个Auth::user() ? Auth::user()->id : null 吗?
    【解决方案3】:

    我认为您的代码需要更新如下:

    public function boot()
    {
        if(Auth::user()){
            view()->composer('*', function($view){
            $view->with('user', Auth::user());
    
            $counter = DB::table('notifications')->where('user_notifications.user_id', Auth::user()->id)->count();
            View::share('counter', $counter);
            });
       }
    

    希望这对你有用!

    【讨论】:

    • 它仍然给出同样的错误.. 我不能在方法开始时使用检查,因为$view->with('user', Auth::user()); 让我访问身份验证
    猜你喜欢
    • 1970-01-01
    • 2018-10-27
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    相关资源
    最近更新 更多