Search code examples
routeslocalehttp-redirectlaravel-5.5

Laravel language switching not working for some routes in Laravel 5.5


I have successfully set language switcher in my project. It works very fine some pages but not in some pages. This is my language switching form:

<form id="language_switcher_form"  action="language" method="post">
    <select     name="locale" id="language_switcher">
        <option value="en" {{App::getLocale()=='en'?' selected' : ''}} class="mt-english"> English</option>
        <option value="np" {{App::getLocale()=='np'?' selected' : ''}}  class="mt-nepali">Nepali</option>
    </select>
    {{ csrf_field() }}
</form> 

My javascript to submit form is:

$( "#language_switcher" ).change(function() {
  $("#language_switcher_form").submit();
});

My routes for language switching is:

Route::resource('properties', 'PropertiesController');
Route::post('/language', array(
    'Middleware'=>'LanguageSwitcher',
    'uses'=>'LanguageController@index'
));

My middleware:

<?php
namespace App\Http\Middleware;
use Closure;
use App;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Config;

class LanguageSwitcher
{
    public function handle($request, Closure $next)
    {
        App::setLocale(Session::has('locale')? Session::get('locale'): Config::get('app.locale'));
        return $next($request);
    }
}

My language controller is:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;
use Redirect;
use App\Http\Requests;

class LanguageController extends Controller
{
    public function index(){
        if(!\Session::has('locale')){
            \Session::put('locale', Input::get('locale'));
        }
        else{
            session(['locale' => Input::get('locale')]);
        }
        return Redirect::back();
    }
}

When I try to switch the language from homepage or http://localhost/myproject/properties , it works as expected. But when I try to do the same from http://localhost/gharsansar/properties/create it redirects me to http://localhost/gharsansar/properties/language. Similary for http://localhost/gharsansar/properties/12 it redirects to http://localhost/gharsansar/properties/language. What mistake have I made? It throws this error.

Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException No message

Thank you in advance.


Solution

  • please try this :

    <form action="{{ route('switch') }}">
    

    and in route :

    Route::post('/language',array('Middleware'=>'LanguageSwitcher','uses'=>'LanguageController@index'))->name('switch');