php – Property [name] does not exist on this collection instance in Laravel-ThrowExceptions

Exception or error:

I’m trying to view details of a specific post or id. But it’s throwing error. N.B: I want to use get() not first().

Error:

Property [name] does not exist on this collection instance. (View: 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 [View/Read post (details view of a specific post or )]

public function viewPost($id){
    $post=DB::table('posts')
    ->join('categories','posts.category_id','categories.id')
    ->select('posts.*','categories.name')
    ->where('posts.id',$id)
    ->get();

    //return response()->json($post);
    return view('post.viewPost', compact('post'));
}

4. viewPost.blade.php Final view page

Category name: {{ $post->name }}

{{ $post->title }}

img src="{{URL::to($post->image)}}" style="height: 200px; width:400px;"

{{ $post->details }}
  1. But when I use return response()->json($post); it’s giving me data as expected. Like:

enter image description here

How to solve:

The get() method returns a Collection, which is an object wrapper for arrays in Laravel. Since you have a where clause on id, you want a single object and you can use first() instead.

$post = DB::table('posts')
    ->join('categories', 'posts.category_id', 'categories.id')
    ->select('posts.*', 'categories.name')
    ->where('posts.id', $id)
    ->first();

Alternative solution

Even thou your solution is very optimal, there is a more practical solutions for dealing with relationships include in Laravel.

Define your relationship.

class Post {
    public function category() {
        return $this->belongsTo(Category::class);
    }
}

Now eager load the category, before the query is executed.

$post = Post::with('category')->find($id);

In your view you can simply access the category name through the relationships, in a fairly optimal query execution plan. Meanwhile your code is way more readable and maintainable and in my opinion this is the correct Laravel way of doing this.

{{ $post->category->name }}

Leave a Reply

Your email address will not be published. Required fields are marked *