Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel中的此集合实例上不存在属性[name]_Php_Laravel - Fatal编程技术网

Php Laravel中的此集合实例上不存在属性[name]

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}'

我试图查看特定帖子或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 }}