Search code examples
laravelfunctionsortingviewcontroller

Laravel : sorting filter brands doesn't works but error points to an other function (which works)


I am trying to display my categories and brands when I click on them (a screen if needed). Categories work, but not brands. When I click on a brand, I get the error "Call to a member function products() on null" pointing to the line in the categories function ->products()->paginate(12);. Why is this happening, and how can I fix it? Thank you.

// My brand route
Route::get('catalogue/marque/{marque?}', 'App\Http\Controllers\CatalogueController@marque')->name('catalogue.marque');

// My brand function
function marque($slug)
{
    $products = \App\Models\Brand::where('slug', $slug)
                 ->first()
                 ->products()->paginate(12);

    $categories = \App\Models\Category::all();
    $brands = \App\Models\Brand::all();

    return view('catalogue.index', compact('products', 'categories', 'brands'));
}

// My view
<ul>
@foreach($brands as $brand)
    <li><a href="{{ route('catalogue.marque', ['slug' => $brand->slug]) }}">{{ $brand->name }}</a></li>
@endforeach
</ul>

Solution

  • Well Though I have given my answer through my comments Still I think I need to clarify some key-points about the code.

    Here are these points.

    1. When you use optional-parameter(i.e {marque?}) in routes you need to properly map the parameter to its corresponding Controller's method (in your case marque($slug)) like this.

      function marque(?string $marque = null) { ....... ..... }

      For more information check the docs link

      https://laravel.com/docs/11.x/routing#parameters-optional-parameters

    2. When you pass the parameter value to route('catalogue.marque', ['slug' => $brand->slug]) , It does not match with the route-defination. So inside marque($slug) method it doesn't get any matching records through $slug during fetching of the Brand model and returns null. Hence when you try to use paginate(12) on the fetched result you are getting this error.

      Call to a member function products() on null