PHP code example of skyraptor / laravel-localized-routes
1. Go to this page and download the library: Download skyraptor/laravel-localized-routes 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/ */
skyraptor / laravel-localized-routes example snippets
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class, // <= after this
//...
\CodeZero\LocalizedRoutes\Middleware\SetLocale::class,
//...
\Illuminate\Routing\Middleware\SubstituteBindings::class, // <= before this
];
'use_locale_middleware' => true
protected $middlewareGroups = [
'web' => [
\Illuminate\Session\Middleware\StartSession::class, // <= after this
//...
\CodeZero\LocalizedRoutes\Middleware\SetLocale::class,
//...
\Illuminate\Routing\Middleware\SubstituteBindings::class, // <= before this
],
];
app()->setLocale('en');
app()->getLocale(); // 'en'
$url = route('home'); // /home (normal routes have priority)
$url = route('about'); // /en/about (current locale)
// Get specific locales...
// This is most useful if you want to generate a URL to switch language.
$url = route('about', [], true, 'en'); // /en/about
$url = route('about', [], true, 'nl'); // /nl/about
// You could also do this, but it kinda defeats the purpose...
$url = route('en.about'); // /en/about
$url = route('en.about', [], true, 'nl'); // /nl/about
return redirect()->route('home'); // non-localized route, redirects to /home
return redirect()->route('about'); // localized route, redirects to /en/about (current locale)
use CodeZero\LocalizedRoutes\ProvidesRouteParameters;
use Illuminate\Database\Eloquent\Model;
class Post extends Model implements ProvidesRouteParameters
{
public function getRouteParameters($locale = null)
{
return [
$this->id,
$this->getSlug($locale) // Add this method yourself of course :)
];
}
}
public function resolveRouteBinding($value)
{
// Perform the logic to find the given slug in the database...
return $this->where($this->getRouteKeyName().'->'.app()->getLocale(), $value)->firstOrFail();
}
// Use the post slug as the route parameter instead of the default ID
Route::get('posts/{post:slug}', ...);
public function resolveRouteBinding($value, $field = null)
{
// Perform the logic to find the given slug in the database...
return $this->where($field ?? $this->getRouteKeyName().'->'.app()->getLocale(), $value)->firstOrFail();
}