PHP code example of mphpmaster / laravel-translatable
1. Go to this page and download the library: Download mphpmaster/laravel-translatable 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/ */
mphpmaster / laravel-translatable example snippets
$book = Book::first();
echo $book->translate('en')->title; // English
App::setLocale('en');
echo $book->title; // English
App::setLocale('fr');
echo $book->title; // French
$book = Book::first();
echo $book->translate('en')->title; // English
$book->translate('en')->title = 'English Lang';
$book->save();
$book = Book::first();
echo $book->translate('en')->title; // English Lang
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class, // <= after this
//...
\mPhpMaster\Translatable\Middleware\SetLocale::class,
//...
\Illuminate\Routing\Middleware\SubstituteBindings::class, // <= before this
];
'use_locale_middleware' => true
protected $middlewareGroups = [
'web' => [
\Illuminate\Session\Middleware\StartSession::class, // <= after this
//...
\mPhpMaster\Translatable\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 mPhpMaster\Translatable\ProvidesRouteParameters;
use Illuminate\Database\Eloquent\Model;
class Book 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('slug->'.app()->getLocale(), $value)->firstOrFail();
}