Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shahr's avatar
Level 10

Property [id] does not exist on this collection instance.

Look at my codes and I have three tables,

  • galleries
  • categories
  • category_gallery

Gallery.php

public function categories()
{
    return $this->belongsToMany(Category::class);
}

GalleryController.php

public function gallery()
{
    $galleries = Gallery::whereNotNull('image')->latest()->paginate(25);
    $categories = Category::where('parent_id', 42)->with('galleries')->get();
    return view('Home.galleries', compact('galleries', 'categories'));
}

galleries.blade.php

 {{ dd($gallery->categories->id) }}

I get this error

Property [id] does not exist on this collection instance.

0 likes
12 replies
a4ashraf's avatar

@oxbir

Try this

$galleries = Gallery::with('category')->whereNotNull('image')->latest()->paginate(25);
    
$categories = Category::where('parent_id', 42)->with('galleries')->get();
    
return view('Home.galleries', compact('galleries', 'categories'));
shahr's avatar
Level 10

I get this error.

Call to undefined relationship [category] on model [App\Gallery].

Scooby's avatar

Calling the wrong method name?

Gallery::with('categories')...
a4ashraf's avatar

@oxbir

Please create Model function for category in your Gallery Model

a4ashraf's avatar

@oxbir

Try now


$galleries = Gallery::with('categories')->whereNotNull('image')->latest()->paginate(25);
    
$categories = Category::where('parent_id', 42)->with('galleries')->get();
    
return view('Home.galleries', compact('galleries', 'categories'));
shahr's avatar
Level 10

I created model of Gallery and Category already.

a4ashraf's avatar

@oxbir

try this

$galleries = Gallery::with('categories')->whereNotNull('image')->latest()->paginate(25);
    
$categories = Category::where('parent_id', 42)->with('galleries')->get();
    
return view('Home.galleries', compact('galleries', 'categories'));
shahr's avatar
Level 10

I get this error again

Property [id] does not exist on this collection instance.

shahr's avatar
Level 10

This...

Property [id] does not exist on this collection instance. (View: C:\xampp\htdocs\sites\blog\resources\views\Home\galleries.blade.php)

a4ashraf's avatar
a4ashraf
Best Answer
Level 33

@oxbir

you are getting more than one rows in. $gallery->categories

use nested foreach in your blade file


@foreach($gallery->categories as $category)
    
your html 

@endforeach
1 like

Please or to participate in this conversation.