Search code examples
laraveleloquentslug

Get Items by another table ID using "slugs"


I have a very simple db model consisting of two tables Items and Categories.

Items Table

ID I Title I Category_id

Categories Table

ID I Name I Slug

At this moment I can filter items by one particular category with something like www.myapp.com/tags/1.

Route::get('tags/{category?}', array('as'=>'itemstag', 'uses'=>'ItemsController@show_items'));

And this is how the controller looks like.

   public function show_items($category = NULL)
{

    if($category == NULL)
        return View::make('items/index', ['items' => Item::where('publishtime', '<', date('Y-m-d H:i:s'))->orderBy('created_at','Desc')->paginate(24),'categories' => Category::all()]);
    else
        return View::make('items/index', ['items' => Item::where('publishtime', '<', date('Y-m-d H:i:s'))->orderBy('created_at','Desc')->where('category_id','=',$category)->paginate(24),'categories' => Category::all()]);

}

The thing is I want to make my urls more "pretty" but if I pass the slug to the controller then I can't evaluate the condition because I don't have $slug on my items model. Should I do a join here? What is the correct way to implement slugs in this case?


Solution

  •     $items = Item::where('publishtime', '<', date('Y-m-d H:i:s'))
             ->orderBy('created_at','Desc')
             ->whereHas('category', function ($q) use ($category){
                 $q->where('slug','=',$category);
             })
             ->paginate(24);