I am working on Laravel localization. I have all done but facing issue. When I change language from dropdown page successfully transalated but language in ROUTE not change.
In web.php I have setup this,
Route::get('/', function () {
return redirect(app()->getLocale());
});
Route::get('language/change', [LocalizationController::class, 'changeLanguage'])->name('changeLang');
Route::group(
[
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}'],
'middleware' => 'setlocale'
],function () {
Route::get('/', [MainController::class, 'index'])->name('main.index');
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::group(['middleware' => ['auth']], function () {
//
});
});
I have added below code in Middleware,
public function handle(Request $request, Closure $next)
{
if (session()->has('locale')) {
App::setLocale(session()->get('locale'));
}
return $next($request);
}
In view file I have added this code,
<select class="form-control languageSelector">
<option {{ session()->get('locale') == 'en' ? 'selected' : '' }} value="en">🇺🇸 <span style="font-weight: bolder !important">En</span></option>
<option {{ session()->get('locale') == 'fr' ? 'selected' : '' }} value="fr">🇫🇷 <span style="font-weight: bolder !important">Fr</span></option>
</select>
$(document).ready(function(){
var url = '{{ route('changeLang') }}';
$('.languageSelector').change(function(){
window.location.href = url + "?lang="+ $(this).val();
});
});
when I select language french from dropdown in route always see EN.
In Controller I have added,
public function changeLanguage(Request $request)
{
App::setLocale($request->lang);
session()->put('locale', $request->lang);
return redirect()->back();
}
How can I solve it?
Thanks Stack overflow. I have solve it by using this technique,
public function changeLanguage(Request $request)
{
App::setLocale($request->lang);
session()->put('locale', $request->lang);
$url = url()->previous();
$route = app('router')
->getRoutes($url)
->match(app('request')->create($url))
->getName();
return redirect()->route($route, ['locale' => $request->lang]);
}
The better way to use the session for this purpose because its a cheap way to define URL with language code, and here is the best way you can use on anywhere. you can follow all instruction
web.php
kernal.php
middleware
at the end you wrote this line of code in controller?
[1]: https://i.stack.imgur.com/p63eB.png
Related
In my laravel application whenever I go to this route: admin/slider-groups I get the following error message:
We have following routes.
/slider-groups
/slider-groups/1
/slider-groups/1/sliders/create
/slider-groups/1/sliders/10/edit
blade.php
<a href="{{ route('admin::sliders.index') }}" class="mr-1">
web.php
Route::group([
'prefix' => 'admin',
'as' => 'admin::',
], function() {
Route::resource('slider-groups', 'Admin\SliderGroupController');
Route::prefix('slider-groups/{sliderGroup}')->group(function(){
Route::resource('sliders', 'Admin\SliderController');
});
});
SliderGroupController.php
public function index(Request $request)
{
if ($request->search) {
$sliderGroups = SliderGroup::search($request->search)->paginate(30);
} else {
$sliderGroups = SliderGroup::paginate(30);
}
if ($sliderGroups->count() == 0 && $request->search ) {
msg()->warning('دقت کنید', 'هیچ رکوردی یافت نشد.');
}
return view('slider::admin.groups.index', compact('sliderGroups'));
}
To note I'm not including all the html code of index.blade.php as it's too long the only blade code is from what i have pasted.
Since you are prefixing siderGroup, you need to pass the $sliderGroup->id to each route in
Route::resource('sliders', 'Admin\SliderController');
For example do:
Link
instead of:
Link
in web.php :
Route::group(['middleware'=>['checklang','checkmoney']],function(){
Route::get('/', function () {
return redirect('/'.session()->get('lang'));
});
Route::group([
'prefix' => '{locale}',
'where'=>['locale'=>'[a-zA-Z]{2}']],
function() {
Route::get('/tour/{id}','HomeController#getTours');
});
});
in HomeContoller :
public function getTours($id){
dd($id);
}
when trying to access url : example.com/en/tour/5
getting result
en , but should be 5
Where is a problem and how to solve it?
Your route has 2 variables, {locale} and {id}, but your Controller method is only referencing one of them. You need to use both:
web.php:
Route::group(['prefix' => '{locale}'], function () {
...
Route::get('/tour/{id}', 'HomeController#getTours');
});
HomeController.php
public function getTours($locale, $id) {
dd($locale, $id); // 'en', 5
}
Note: The order of definition matters; {locale} (en) comes before {id} 5, so make sure you define them in the correct order.
I am getting either of 2 errors one after the other.
While submitting the form either I get the error below
The page has expired due to inactivity. Please refresh and try again.
Or this error
InvalidArgumentException
Route [register/user/image] not defined.
I have cross checked everything unable to find out the real cause.
Routes/web.php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::prefix('manage')->middleware('role:superadministrator|administrator|editor|member')->group(function() {
Route::get('/', 'ManageController#index');
Route::get('/carezone', 'ManageController#carezone')->middleware('role:superadministrator|administrator')->name('manage.dashboard');
Route::get('/dashboard', 'ManageController#dashboard')->name('manage.dashboard');
});
Route::middleware('role:superadministrator|administrator|editor|member|subscriber')->group(function() {
Route::get('register/user/details', 'RegisterUserController#showUserDetailsForm')->name('register.user.details');
Route::post('register/user/details', 'RegisterUserController#postUserDetailsForm')->name('register.user.details');
Route::get('/api/username/unique', 'RegisterUserController#apiCheckUniqueUserName')->name('api.username.unique');
Route::get('register/user/image', 'RegisterUserController#showUserImageForm')->name('register.user.image');
Route::post('register/user/image', 'RegisterUserController#postUserImageForm')->name('register.user.image');
});
Route::get('/email/unique', 'RegisterUserController#checkUniqueEmail')->name('email.unique');
Route::get('/get/city', 'RegisterUserController#ajaxGetCity')->name('get.city');
Route::get('/registration', 'RegisterUserController#showRegistrationForm')->name('registration');
Route::get('/home', 'HomeController#index')->name('home');
RegisterUserController.php
/*function to redirect user to user details page after register page*/
public function showUserDetailsForm() {
$states = State::all();
return view('pages.registration.registerUserDetails', ['states'=> $states]);
}
/*function to post and save data to the database*/
public function postUserDetailsForm(Request $request) {
$validatedData = $request->validate([
'username' => 'required|alpha_num|min:6|max:20|unique:details,username',
'dob' => 'required|date',
'gender' => 'required|string',
'state' => 'required|numeric',//validation rule for max min values
'city' => 'required|numeric',//validation rule for max min values
]);
$post = new Detail;
$post->user_id = Auth::user()->id;
$post->username = $request->username;
$post->dob = $request->dob;
$post->gender = $request->gender;
$post->state_id = $request->state;
$post->city_id = $request->city;
$post->save();
return redirect()->route('register/user/image');
}
Small Portion Of my form
<form id="registerUserDetails" class="form-horizontal clearfix" method="POST" action="{{ route('register.user.details') }}" role="form" novalidate>
{{ csrf_field() }}
.
.
.
.
<button type="submit" class="tabButton">Next</button>
</form>
<script>Javascript Validation here</script>
To solve the second error you must fix your route name on your controller method (and everywhere):
Actual:
return redirect()->route('register/user/image');
Correct:
return redirect()->route('register.user.image');
For solving the first error add the csrf field {{ csrf_field() }} to form
And for the second one, you route's name is register.user.image
so set the form's action like this
<form action=" {{ route('register.user.image') }} ">
Is thier anyway to do somethins like this ,
in web.php
Route::get('/test', 'testController#test');
in test Controller
public function test ($url)
{
//while $url store test in route
}
I know only if I send parameter I have to use
Route::get('/{test}', 'testController#test');
UPDATE
I want to do something like this
Route::get('/test', 'testController#test');
Route::get('/test2', 'testController#test');
in my controller
public function test ($url)
{
while $url store test,test2in route
}
LASTEST UPDATE
I dont want to use {url}
I want to make /test = $url when I enter to url/test
In my web.php I use this
Route::get('/test', 'testController#test');
Route::get('/test2', 'testController#test');
The reason that I want to do something like this because I want to make 1 function that alll route can use In my controller I do this .
public function test($url,$preview=null)
{
//$url shoud be test or test 2
try {
$test = (isset($preview)) ? test::where('test.id',$url)->first()
} catch (\Exception $e) {
return redirect('notfound');
}
}
I dont want todo something like this
Route::get('/test', 'testController#test');
Route::get('/test2', 'testController#test');
and In controller
public function test($preview=null)
{
//$url shoud be test or test 2
try {
$test = (isset($preview)) ? test::where('test.id','test)->first()
} catch (\Exception $e) {
return redirect('notfound');
}
}
You need to combine both elements
Route::get('/test/{url}', 'testController#test');
want to make /test = $url
You can't, but you can have /test?foo=$url instead. So you keep your route like
Route::get('/test', 'testController#test');
Then add Request $request as controller method argument (and you remove $url)
public function test(Request $request) {
...
Finally you obtain your url with
$url = $request->input('foo');
Your Route
Route::post('/test', 'testController#test')->name('test);
If you use blade.
<a href="{{ route('test') }}"
onclick="event.preventDefault();
document.getElementById('test_id').submit();">
Test Click
</a>
{!! Form::open(['url' => route('test'), 'method' => 'post', 'id' => 'test_id']) !!}
<input type="hidden" name="url" value="{{ $url}}">
{!! Form::close() !!}
In your controller.
public function test(Request $request)
{
$data = $request->all();
$url = $data['url'];
//do something with your url...
}
im using Laravel 5, and i have this route:
Route::group(['prefix' => '{lang}/', 'middleware' => 'SetLanguage'], function($lang){
//element Show
Route::get('/'.trans('routes.element-container').'/{slugName}', 'ElementController#showByName');
});
My middleware is this:
public function handle($request, Closure $next)
{
if (in_array($request->lang, config('app.all_langs'))){
//exit("SETTING ON ".$request->lang);
App::setLocale($request->lang);
}else{
//exit("SETTING ON en");
App::setLocale('en');
}
return $next($request);
}
If i un-comment the two exit it works, but, the function "trans" on route side is not working, seems to trans only in default lang.
why the "trans" function is called before the middleware?
I have test with 'before' and 'after', but no work...
If I understood you correctly, you could consider something like this:
Route::group(['prefix' => '{lang}/', 'middleware' => 'SetLanguage'], function() {
foreach (config('app.all_langs') as $language) {
$translatedRoute = trans('routes.element-container', [], $language);
Route::get("/$translatedRoute/{slugName}", 'ElementController#showByName');
}
});
But this will also register routes for e.g. /de/element-container/element-a.
Alternative:
foreach (config('app.all_langs') as $language) {
Route::group(['prefix' => $language, 'middleware' => 'SetLanguage'], function() {
$translatedRoute = trans('routes.element-container', [], $language);
Route::get("/$translatedRoute/{slugName}", 'ElementController#showByName');
});
}
This will register /en/element-container/element-a and /de/Elemente-Behälter/element-a, but not /de/element-container/element-a