873 0 0 0
Last Updated : 2025-04-28 22:05:06
In this snippet I will teach you how to create your laravel project and use multi language but with the route prefix
Hello Guys,
In this snippet I will teach you how to create your laravel project and use multi languages using route prefixex in it.
This way depends on creating a prefix with in URL that indicates to the locale language like EN or AR
So the workflow for this method is :
1- add prefix before all your routes and apply condition to control what the user will type there like this
Route::group([
'prefix' => '{locale?}',
'where' => ['locale' => '[a-zA-Z]{2}'],
'middleware' => 'SetLocale',
], function() {
Route::middleware('IsVendorLoggedIn')->prefix('vendor')->name('vendor.')->group(function() {
##------------------------------------------------------- INDEX PAGE
Route::view('/index', "layout::vendor.index")->name('index'); // THIS VIEW SYNTAX DEPENDS ON LARAVEL MODULAR
});
});
2- Now you have to create a new middleware to check if that prefix exists with specific value and then set the locale of the project to that language like this
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\View;
class SetLocale
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
$lang = $request->segment(1);
if ($lang == 'en' || $lang == 'ar') {
App::setLocale($lang);
}
URL::defaults(['locale' => app()->getLocale()]);
return $next($request);
}
}
3- The last thing you have to do is to pass the value of the wanted language prefix in all of your route link like this
<a class="nav-link nav-link-style" href="{{ route('vendor.mode.change', app()->getLocale()) }}">text</a>
BUT you can't do this to all of your route links in the project, So we add this code in the above middleware
URL::defaults(['locale' => app()->getLocale()]);
This will make the default value for the locale for all of your routes is to set to project locale
The last thing you want for now is to create your action to select the language you want and reload your page
Hope you like it