I am using Laravel11.1.1 to build a school website, but the Language switch button is not working as the page shows only English language , actually clicking the arabic button doesn’t change the language.
LanguageController code:
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use IlluminateSupportFacadesSession;
class LanguageController extends Controller
{
public function switchLang($locale)
{
if (in_array($locale, ['en', 'ar'])) {
Session::put('locale', $locale);
Log::info('Locale switched to: ' . $locale);
} else {
Session::put('locale', config('app.locale'));
Log::info('Locale switched to default: ' . config('app.locale'));
}
return redirect()->back();
}
}
```````
LanguageMiddlware
```````
<?php
namespace AppHttpMiddleware;
use Closure;
use IlluminateHttpRequest;
use IlluminateSupportFacadesApp;
use IlluminateSupportFacadesSession;
class LanguageMiddleware
{
public function handle(Request $request, Closure $next)
{
$locale = Session::get('locale', config('app.locale'));
App::setLocale($locale);
Log::info('Current locale: ' . $locale);
return $next($request);
}
}
The Middlware Registration in bootstrap/app.php
<?php
// bootstrap/app.php
use IlluminateFoundationApplication;
use AppHttpMiddlewareLanguageMiddleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function ($middleware) {
$middleware->append(LanguageMiddleware::class);
})
->withExceptions(function ($exceptions) {
//
})
->create();
resources/lang/ar/messages.php
<?php
return [
'home' => 'الصفحة الرئيسية',
'news' => 'الأخبار',
'gallery' => 'المعرض',
'classes' => 'الفصول الدراسية',
'contact' => 'اتصل بنا',
'join_us' => 'انضم إلينا',
'welcome' => 'مرحبا بكم في مدرسة الطيف الخاصة',
];
````````
resources/lang/en/messages.php
```````
<?php
return [
'home' => 'Home',
'news' => 'News',
'gallery' => 'Gallery',
'classes' => 'Classes',
'contact' => 'Contact',
'join_us' => 'Join Us',
'welcome' => 'Welcome to Tayf Private School',
];
```````
resources/viwes/layouts/app.blade.php
```````
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ config('app.name', 'Tayf Private School') }}</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
@vite('resources/css/app.css')
</head>
<body>
<header>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="{{ route('home') }}">{{ config('app.name', 'Tayf Private School') }}</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="{{ route('home') }}">@lang('messages.home')</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('news') }}">@lang('messages.news')</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('gallery') }}">@lang('messages.gallery')</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('classes') }}">@lang('messages.classes')</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('contact.index') }}">@lang('messages.contact')</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('join.index') }}">@lang('messages.join_us')</a>
</li>
</ul>
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="{{ route('lang.switch', ['locale' => 'en']) }}">English</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('lang.switch', ['locale' => 'ar']) }}">العربية</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<main role="main">
<div class="container mt-4">
@yield('content')
</div>
</main>
<footer class="footer mt-auto py-3 bg-light">
<div class="container text-center">
<span class="text-muted">© {{ date('Y') }} {{ config('app.name', 'Tayf Private School') }}</span>
</div>
</footer>
@vite('resources/js/app.js')
</body>
</html>
web.php
<?php
use IlluminateSupportFacadesRoute;
use AppHttpControllersHomeController;
use AppHttpControllersGalleryController;
use AppHttpControllersNewsController;
use AppHttpControllersClassController;
use AppHttpControllersContactController;
use AppHttpControllersJoinController;
use AppHttpControllersLanguageController;
// routes/web.php
Route::get('lang/{locale}', [LanguageController::class, 'switchLang'])->name('lang.switch');
// Other routes
Route::get('/', [HomeController::class, 'index'])->name('home');
Route::get('/news', [NewsController::class, 'index'])->name('news');
Route::get('/gallery', [GalleryController::class, 'index'])->name('gallery');
Route::get('/classes', [ClassController::class, 'index'])->name('classes');
Route::get('/contact', [ContactController::class, 'index'])->name('contact.index');
Route::post('/contact', [ContactController::class, 'store'])->name('contact.store');
Route::get('/join', [JoinController::class, 'index'])->name('join.index');
Route::post('/join', [JoinController::class, 'store'])->name('join.store');
`
also here is my config/app.php
<?php
return [
'name' => env('APP_NAME', 'Laravel'),
'env' => env('APP_ENV', 'production'),
'debug' => (bool) env('APP_DEBUG', false),
'url' => env('APP_URL', 'http://localhost'),
'timezone' => env('APP_TIMEZONE', 'UTC'),
'locale' => 'en',
'fallback_locale' => 'en',
'available_locales' => ['en', 'ar'],
'faker_locale' => env('APP_FAKER_LOCALE', 'en_us'), // Faker locale for generating fake data
'cipher' => 'AES-256-CBC',
'key' => env('APP_KEY'),
'previous_keys' => array_filter(explode(',', env('APP_PREVIOUS_KEYS', ''))),
'maintenance' => [
'driver' => env('APP_MAINTENANCE_DRIVER', 'file'),
'store' => env('APP_MAINTENANCE_STORE', 'database'),
],
];
and config/session/app.php
<?php
use IlluminateSupportStr;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option determines the default session driver that is utilized for
| incoming requests. Laravel supports a variety of storage options to
| persist session data. Database storage is a great default choice.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to expire immediately when the browser is closed then you may
| indicate that via the expire_on_close configuration option.
|
*/
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it's stored. All encryption is performed
| automatically by Laravel and you may use the session like normal.
|
*/
'encrypt' => env('SESSION_ENCRYPT', false),
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When utilizing the "file" session driver, the session files are placed
| on disk. The default storage location is defined here; however, you
| are free to provide another location where they should be stored.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table to
| be used to store sessions. Of course, a sensible default is defined
| for you; however, you're welcome to change this to another table.
|
*/
'table' => env('SESSION_TABLE', 'sessions'),
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using one of the framework's cache driven session backends, you may
| define the cache store which should be used to store the session data
| between requests. This must match one of your defined cache stores.
|
| Affects: "apc", "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the session cookie that is created by
| the framework. Typically, you should not need to change this value
| since doing so does not grant a meaningful security improvement.
|
*/
'cookie' => env('SESSION_COOKIE', Str::slug(env('APP_NAME', 'laravel'), '_').'_session'),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application, but you're free to change this when necessary.
|
*/
'path' => env('SESSION_PATH', '/'),
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| This value determines the domain and subdomains the session cookie is
| available to. By default, the cookie will be available to the root
| domain and all subdomains. Typically, this shouldn't be changed.
|
*/
'domain' => env('SESSION_DOMAIN', null),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE', false),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. It's unlikely you should disable this option.
|
*/
'http_only' => env('SESSION_HTTP_ONLY', true),
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" to permit secure cross-site requests.
|
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => env('SESSION_SAME_SITE', 'lax'),
/*
|--------------------------------------------------------------------------
| Partitioned Cookies
|--------------------------------------------------------------------------
|
| Setting this value to true will tie the cookie to the top-level site for
| a cross-site context. Partitioned cookies are accepted by the browser
| when flagged "secure" and the Same-Site attribute is set to "none".
|
*/
'partitioned' => env('SESSION_PARTITIONED_COOKIE', false),
];
`
I’ve tried to make my website multi-languale , but only the english works .
Oussama_Seddiki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.