Shiva's avatar

Getting a gallery item from a pivot table

I'm using laravel 4 and I'm trying to get all the gallery items that belongs to a category depending on the menu. For example I have a menu ID of 4 and the category ID that belongs to that menu ID is 3.

So what I would like is when the menu is selected then the category that belongs to that menu displays the items that belong to the category.

I really hope that made sense. So far I've only managed to get the menu to display the correct category but I'm having an issue trying to get the gallery items to display.

I'm getting this error

Call to undefined method Illuminate\Database\Eloquent\Collection::gallery() 

Which means that it isn't finding the gallery function in my Category model.

my HomeController.php

        //gets the menu id
        $category = Menu::find($id);

        //Displayes the category that was saved
        $gallery_test = $category->category()
                                    ->select('category.id')
                                    ->lists('id');



        //Gets the id from $gallery_test
        $test = Category::find($gallery_test);

        //This should display the items that matches the category
        $gal_test = $test->gallery()                                    
                        ->select('gallery.id')
                        ->lists('id');
0 likes
6 replies
Shiva's avatar

@fraserk - sure here it is:

<?php

class Category extends \Eloquent {
    //Allows the fields in the array to be fillable
    protected $fillable = array('title', 'image');
    //Doesn't allow the id to be changed
    protected $guarded = array('id');

    protected $table = 'category';

    //Validation rules
    public static $rules = array(
        
        );

    //Connects the gallery table with the category table
    public function gallery(){
        return $this->belongsToMany('Gallery', 'category_gallery', 'category_id', 'gallery_id');
    }

    //Connects the menu table with the category table
    public function menu(){
        return $this->belongsToMany('Menu', 'category_menu', 'category_id', 'menu_id');
    }
}
Shiva's avatar

Does anyone know where I'm going wrong.

Please or to participate in this conversation.