'Laravel: Redirect back missing url and return 404 page

I have a problem with redirect back in laravel 8. When I access page url like: localhost:8000 and change languages from english to japan. Browser back to localhost:8000 and update new selected language. But when I access dynamic url like localhost:8000/post/tin-tuc/recruiment and select language. Browser back to url like this localhost:8000/post/tin-tuc/language/ja and show 404 page error. Tks for your help.

Here is my code:

Web.php

Route::get('/', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('post/{category_slug}/{content_slug}', [App\Http\Controllers\PostController::class, 'detail'])->name('post');
Route::get('post-detail/{content_slug}/{post_slug}', [App\Http\Controllers\PostDetailController::class, 'detail'])->name('post.detail');

Route::get('language/{locale}', function ($locale) {
    app()->setLocale($locale);
    session()->put('locale', $locale);
    return Redirect::intended('/');
});

Localization middleware

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

config/app.php

'locale' => 'en',
'fallback_locale' => 'en',
'available_locales' => [
        'English' => 'en',
        //'Vietnamese' => 'vi',
        'Japanese' => 'ja',
],

app/http/Provider/AppServiceProvider

public function boot()
    {
        view()->composer('partials.language_switcher', function ($view) {
            $view->with('current_locale', app()->getLocale());
            $view->with('available_locales', config('app.available_locales'));
        });
        
        $categoriesGeneral = Category::where('status', config('constants.status.Alive'))->get();
        view()->share('categoriesGeneral', $categoriesGeneral);

        $contentItems = Content::join('categories', 'contents.category_id', '=', 'categories.id')
            ->where('contents.status', config('constants.status.Alive'))
            ->where('categories.status', config('constants.status.Alive'))
            ->select('contents.*', 'categories.category_name', 'categories.slug AS category_slug')
            ->get();
        view()->share('contentItems', $contentItems);
    }



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source