Php Laravel中的此集合实例上不存在属性[name]
我试图查看特定帖子或id的详细信息。但它抛出了错误。注意:我想使用Php Laravel中的此集合实例上不存在属性[name],php,laravel,Php,Laravel,我试图查看特定帖子或id的详细信息。但它抛出了错误。注意:我想使用get()而不是first() 错误: 此集合实例上不存在属性[name]。(视图:C:\xampp\htdocs\myBlog\resources\views\post\viewPost.blade.php) 1。allPostView.blade.php a href="{{ URL::to('view/post/'.$row->id) }}" 2。web.php Route::get('view/post/{id}'
get()
而不是first()
错误:
此集合实例上不存在属性[name]。(视图:C:\xampp\htdocs\myBlog\resources\views\post\viewPost.blade.php)
1。allPostView.blade.php
a href="{{ URL::to('view/post/'.$row->id) }}"
2。web.php
Route::get('view/post/{id}','PostController@viewPost');
3。PostControler.php[查看/阅读帖子(特定帖子或帖子的详细视图)]
4。viewPost.blade.php最终查看页面
Category name: {{ $post->name }}
{{ $post->title }}
img src="{{URL::to($post->image)}}" style="height: 200px; width:400px;"
{{ $post->details }}
returnresponse()->json($post)时代码>它正在按预期为我提供数据。比如:
get()
返回一个集合,它是Laravel
中数组的对象包装器。由于id上有一个where子句,所以需要一个对象,可以使用first()
$post = DB::table('posts')
->join('categories', 'posts.category_id', 'categories.id')
->select('posts.*', 'categories.name')
->where('posts.id', $id)
->first();
替代解决方案
即使您的解决方案非常优化,也有一个更实用的解决方案用于处理关系,包括Laravel
定义你的关系
class Post {
public function category() {
return $this->belongsTo(Category::class);
}
}
现在,在执行查询之前加载类别
$post = Post::with('category')->find($id);
在您的视图中,您可以简单地通过关系访问类别名称,这是一个相当优化的查询执行计划。同时,您的代码更具可读性和可维护性,我认为这是正确的Laravel
方法
{{ $post->category->name }}
{{ $post->category->name }}