如何在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();更多推荐
发布评论