Search code examples
phplaravellaravel-5routes

Add query parameter to existing parameters with route-helper


I use the route-helper ({{ route('routename') }}) in my Blade template files to filter and/or sort the results of the page.

What is the easiest way to attach a parameter to the previous ones?

As an example:

I visit the page /category1 and see some products. Now I use the sorting which changes the URL to /category1?sort_by=title&sort_order=asc

If I use another filtering now, I would like the parameter to be appended to the current one. So to /category1?sort_by=title&sort_order=asc&filter_by=year&year=2017 but the result is only /category1?filter_by=year&year=2017 .

I create the Urls with the route-helper like:

route('category.show', [$category, 'sort_by' => 'title', 'sort_order' => 'asc'])
route('category.show', [$category, 'filter_by' => 'year', 'year' => $year])

Solution

  • You could probably use something like:

    $new_parameters = ['filter_by' => 'year', 'year' => $year];
    
    route('category.show', array_merge([$category], request()->all(), $new_parameters]);
    

    to use all previous parameters and add new ones.

    Obviously you might want to use only some of them, then instead of:

    request()->all()
    

    you can use:

    request()->only('sort_by', 'sort_order', 'filter_by', 'year')