PHP code example of mcamara / laravel-localization
1. Go to this page and download the library: Download mcamara/laravel-localization library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
mcamara / laravel-localization example snippets
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel {
/**
* The application's route middleware.
*
* @var array
*/
protected $middlewareAliases = [
/**** OTHER MIDDLEWARE ****/
'localize' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
'localizationRedirect' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
'localeSessionRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
'localeCookieRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleCookieRedirect::class,
'localeViewPath' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationViewPath::class
];
}
// routes/web.php
Route::group(['prefix' => LaravelLocalization::setLocale()], function()
{
/** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/
Route::get('/', function()
{
return View::make('hello');
});
Route::get('test',function(){
return View::make('test');
});
});
/** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/
// An array of attributes can be provided.
// Returns /en/archive/ghosts, /fr/archive/fantômes, /pt/arquivo/fantasmas, etc.
<a href="{{ LaravelLocalization::getURLFromRouteNameTranslated( App::currentLocale(), 'routes.archive', array('category' => 'ghosts')) }}">Ghost Stories</a>
Route::group(['prefix' => LaravelLocalization::setLocale(),
'middleware' => [ 'localize' ]], function () {
Route::get(LaravelLocalization::transRoute('routes.about'), function () {
return view('about');
});
Route::get(LaravelLocalization::transRoute('routes.article'), function (\App\Article $article) {
return $article;
});
//,...
});
public function resolveRouteBinding($slug)
{
return static::findByLocalizedSlug($slug)->first() ?? abort(404);
}
Event::listen('routes.translation', function($locale, $attributes)
{
// Do your magic
return $attributes;
});
class RouteServiceProvider extends ServiceProvider
{
use \Mcamara\LaravelLocalization\Traits\LoadsTranslatedCachedRoutes;
class AppServiceProvider extends ServiceProvider
{
use \Mcamara\LaravelLocalization\Traits\LoadsTranslatedCachedRoutes;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
RouteServiceProvider::loadCachedRoutesUsing(fn() => $this->loadCachedRoutes());
...
}