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'));
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Look at my codes and I have three tables,
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.
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
Please or to participate in this conversation.