php - 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)
解决方案
最后,我找到了答案。这是一个奇怪的解决方案。当你使用 LaravelfirstOrFail()
方法时。错误未登录laravel.log
文件。
所以 snswer 是使用firstOrFail()
而不是first()
. 这不会Trying to get property of non-object
在您的 laravel 日志文件中记录错误。
我不确定为什么会这样,可能是由于 PHP 7 或 laravel 中存在错误?但它奏效了。
推荐阅读
- database - 如何在mongodb中分组并保留所有字段?
- android - 如何在 ViewGroup 中放置中间视图
- java - 如何使用 maven-shade-plugin 解决重叠 spring-boot 资源的警告?
- html - 使用包含页面激活的 Bootstrap 4 nav-pills
- r - 根据名称有条件地将 rbind 或 bind_rows 应用于列表
- java - 运行 jar 时清单主要属性的签名文件摘要无效
- r - 如何使用蛋白质表将名称从蛋白质列表更改为它们的 ID
- python - Python 通过 SSH 隧道连接到 MySQL 服务器
- reactjs - React - 处理需要渲染上层组件的下层组件
- spring-boot - 使用 CachePut 和 Cacheable