如何在Laravel中只找到一条记录时如何防止未定义的属性(how to prevent undefined property when only one record found in Larave

编程入门 行业动态 更新时间:2024-10-25 08:19:08
如何在Laravel中只找到一条记录时如何防止未定义的属性(how to prevent undefined property when only one record found in Laravel)

我试着做一个搜索功能,所以我这样做:

public function search(Request $request) { $query = $request->query('q'); $posts = DB::table('posts')->where('title', 'LIKE', '%'.$query.'%')->get(); return view('admin.dashboard.search')->with('users',$users)->with('posts',$posts); }

但是当我尝试获取结果时,我遇到了一些错误:

未定义的属性:stdClass :: $ user(查看:E:\ laragon \ www \ blog \ resources \ views \ admin \ dashboard \ search.blade.php)

这是错误:

<td><?php echo e($post->user->name); ?></td>

那么我该如何解决呢?

I was try to make a search function so i'm doing like this:

public function search(Request $request) { $query = $request->query('q'); $posts = DB::table('posts')->where('title', 'LIKE', '%'.$query.'%')->get(); return view('admin.dashboard.search')->with('users',$users)->with('posts',$posts); }

but when i try to fetch the result i got some errors like this:

Undefined property: stdClass::$user (View: E:\laragon\www\blog\resources\views\admin\dashboard\search.blade.php)

It was errors in this line:

<td><?php echo e($post->user->name); ?></td>

So how can i fix it?

最满意答案

您必须在搜索查询中急切加载用户,如下所示:

$posts = App\Post::with('user') ->where('title', 'LIKE', '%'.$query.'%') ->get();

You have to eager load the user in your search query like this :

$posts = App\Post::with('user') ->where('title', 'LIKE', '%'.$query.'%') ->get();

更多推荐

本文发布于:2023-07-25 10:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1260042.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   如何防止   未定义   如何在   Laravel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!