Q:

Laravel Eloquent how to get all products in a category with slug

My Productcategory.php has
public function products()
{
    return $this->hasMany('App\Models\Product');
}

And Product.php has
public function productcategory()
{
    return $this->belongsTo('App\Models\Productcategory', 'category_id');
}

Now my route is 
Route::get('gallery/{slug}', 'GalleryController@index');

When URL is something like gallery/print-pattern-client-work, how can I get all products with the same category? I have the following but category_id is an integer and not a slug. So I am not so sure how to do it.
public function index()
{
    $categoryslug = Request::segment(2);
    $products = Productcategory::with('products')->where('category_id',$categoryslug)->get();
...
}

A:

This assumes you have a column named "slug" in your product_categories table. And that your described relations work well.
You could make an accessor in Product.php
public function scopeFindByCategorySlug($query, $categorySlug)
{
    return $query->whereHas('productcategory', function ($query) use ($categorySlug) {
        $query->where('slug', $categorySlug);
    });
}

Then in your controller you call this:
public function index(Request $request, $slug)
{
    $products = Product::findByCategorySlug($slug)->get();
}

Edit: 
As mentioned in comments there is no actual need for an accessor. This is basically all you need (in controller):
public function index(Request $request, $slug)
{
    $products = Product::whereHas('productcategory', function ($query) use ($categorySlug) {
        $query->where('slug', $categorySlug);
    })->get();
}

