Search code examples
phplaravellocalelaravel-routinglaravel-8

Laravel 8 get current route parameters


i have dropdown to change locale in navigation menu. But i dont know that how can i get parameters. How can i get current parameter?

Current parameters: slug,quiz_id,id and etc

navigaiton menu blade:

<a class="dropdown-item" href="{{route(Route::currentRouteName(),'az')}}"> Az </a>
<a class="dropdown-item" href="{{route(Route::currentRouteName(),'en')}}"> En </a>

I have different route.

Web.php

Route::group(['prefix'=>'{language}'],function(){
    Route::get('quiz/{slug}',[MainController::class,'quiz_join'])->name('quiz_join');
    Route::get('quiz/{quiz_id}/questions/{id}', [QuestionController::class, 'destroy'] )->whereNumber('id')->name('question.destroy');
});

enter image description here


Solution

  • If you can't find another way and something else doesn't exist you can use URL::toRoute() and use the current route and pull the parameters from it:

    URL::toRoute($cur = Route::current(), ['language' => 'az'] + $cur->parameters(), true)
    

    You could make a macro for this to simplify it a bit:

    use Illuminate\Support\Facades\Route;
    use Illuminate\Support\Facades\URL;
    
    URL::macro('toCurrentRouteWithParameters', function (array $parameters = [], $absolute = true) {
        $current = Route::current();
        return $this->toRoute($current, $parameters + $current->parameters(), $absolute);
    });
    

    You can add this to a Service Provider's boot method.

    Then you can call it in your Blade template:

    {{ URL::toCurrentRouteWithParameters(['language' => 'az']) }}
    

    If you don't want to use the macro then just try the first part:

    <a class="dropdown-item" href="{{ URL::toRoute($cur = Route::current(), ['language' => 'az'] + $cur->parameters(), true) }}"> Az </a>