首页 > 解决方案 > Laravel 错误:通过 first() 方法访问时尝试获取非对象的属性

问题描述

我将 laravel 5.6 与 PHP 7.1 一起使用。

ErrorException Trying to get property of non-object 当我尝试访问使用 eloquentfirst()方法检索的帖子的属性时, Laravel 会抛出异常。

$post = Blog::select('id', 'title', 'slug')->where('slug', $slug)->first(); //slug is unique column in database
$post->title; //this line cause the error

但是,如果我使用find()方法,它可以正常工作。

$post = Blog::select('id', 'title', 'slug')->find($primarykey);
$post->title; //No error

因为,我不能使用第二种方法,当通过first()方法检索模式时访问这些属性的最佳方法是什么?

编辑:

当我dd($post)使用这两种方法时,我看到了确切的结果。
此外,错误正在登录laravel.log文件,我可以毫无问题地看到该页面。仅当我使用first()方法时才会发生这种情况。

编辑2:

这是我的确切代码:

$viewData['resource'] = Resource::select('id', 'resource_category_id', 'name', 'descp', 'seo_title', 'seo_keywords', 'seo_descp', 'dl_type', 'download', 'thumb', 'image', 'dl_count', 'updated_at')->with(['category' => function($q){
        $q->select('id', 'name', 'slug', 'parent_id');
    }])->where('slug', $slug)->first();
$id = $viewData['resource']->id; // this line throw error, line 126

local.ERROR: Trying to get property of non-object {"exception":"[object] (ErrorException(code: 0): Trying to get property of non-object at E:\\websites\\couponclone\\app\\Http\\Controllers\\ResourceController.php:126)

标签: phplaravel-5error-handlingeloquent

解决方案


最后,我找到了答案。这是一个奇怪的解决方案。当你使用 LaravelfirstOrFail()方法时。错误未登录laravel.log文件。

所以 snswer 是使用firstOrFail()而不是first(). 这不会Trying to get property of non-object在您的 laravel 日志文件中记录错误。

我不确定为什么会这样,可能是由于 PHP 7 或 laravel 中存在错误?但它奏效了。


推荐阅读