Home > other >  middleware doesn't able to get the route parameter in Laravel
middleware doesn't able to get the route parameter in Laravel

Time:07-01

this is my code: the route:

Route::get('lang/change', [LangController::class, 'change'])->name('changeLang');

nav.blade.php

 <div >
                <strong>Select Language: </strong>
            </div>
            <div >
                <select >
                    <option value="en" {{ session()->get('locale') == 'en' ? 'selected' : '' }}>English</option>
                    <option value="ar" {{ session()->get('locale') == 'ar' ? 'selected' : '' }}>Arabic</option>
                </select>
        </div>
          @endauth
        </ul>
      </div>

<span >{{ auth()->user() !=null ? auth()->user()->name : "Guest" }}</span>

    </div>
  </nav>
  <script type="text/javascript">

    var url = "{{ route('changeLang') }}";

    $(".changeLang").change(function(){
        window.location.href = url   "?lang="  $(this).val();
    });

</script>

this is the middleware: (i have registered it in the kernal with web middleware:

public function handle(Request $request, Closure $next)
{
    if (session()->has('locale')) {
        App::setLocale(session()->get('locale'));
    }

    return $next($request);
}

CodePudding user response:

What is the parameter you're passing. All I see is route-url without params

You can check-out this url if you want or just check this block here from laravel documentation

Occasionally you may need to specify a route parameter that may not always be present in the URI. You may do so by placing a ? mark after the parameter name. Make sure to give the route's corresponding variable a default value:

Route::get('/user/{name?}', function ($name = null) {
    return $name;
});

Route::get('/user/{name?}', function ($name = 'John') {
    return $name;
});

I assume you're going with the latest version of Laravel as well Here is the documentation link for routing with parameters Go To Docs

And here is the exact tab where you can find my snippets Laravel Params

CodePudding user response:

In your case there is small misunderstanding.

Your route doesnt accept any of the parameters, you are dealing with request. In you case, the solution should be the next:

    $language = $request->query('lang');
    if (null !== $language) {
        App::setLocale($language);
    }

    return $next($request);
  • Related