Can you share some code on what you want to do? Can't you use a middleware instead?
Session not accessible in bootstrap/app.php file , how to access them
Now i m using localization, so that i want custom error page should be also translated when i changed my language from english to spanish , so that the error page also in spanish language, i have also helper in my file which name is translation($key){} and for localization i m using locale
Thanks in advance
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Support\Str;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
apiPrefix:'api'
)
->withMiddleware(function (Middleware $middleware) {
$middleware->web(append: [
\App\Http\Middleware\IdentifyTenant::class,
\App\Http\Middleware\HandleInertiaRequests::class,
\Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class,
\App\Http\Middleware\SetLocale::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Session\Middleware\StartSession::class,
// \App\Http\Middleware\CheckUserSession::class,
// \App\Http\Middleware\CheckAuthSession::class
]);
$middleware->throttleWithRedis();
$middleware->alias([
// 'check_auth_session' => \App\Http\Middleware\CheckAuthSession::class,
// 'check_user_session' => \App\Http\Middleware\CheckUserSession::class,
]);
//
})
->withExceptions(function (Exceptions $exceptions) {
$exceptions->renderable(function (HttpException $exception) {
// dd(translation_front('select'));
$statusCode = $exception->getStatusCode();
$message = $exception->getMessage();
$translated_message = translation_front(Str::slug($message, '_'));
if ($statusCode == 404) {
$translated_message = translation_front('the_route_dashboardd_could_not_be_found');
}
return response()->view('errors.default', [
'status' => $statusCode,
'message' =>$translated_message ,
], $statusCode);
});
})->create();
this is my helper function
if (!function_exists('translation_front')) {
function translation_front($key)
{
$translate = '-';
$lang = 1;
$language = 'en';
if (session()->has('locale')) {
$language = Session::get('locale');
}
$all_lang = collect(get_language_master());
$item = $all_lang->firstWhere('translation_language_short_form', $language);
if ($item) {
$lang = $item['translation_language_id'] ?? 0;
}
$translation_data = Cache::remember('translation_front-' . $lang, 86400, function () use ($lang) {
$translation = [];
$lang_detail = curl_request(
config('constant.GET_TRANS_ALL_LIST'),
[
'translation_language_id' => $lang,
'api_key' => config('constant.MASTER_API_KEY')
]
);
if (check_valid_array($lang_detail)) {
if ($lang_detail['success_code'] == 1) {
if (check_valid_array($lang_detail['data'])) {
$translation = $lang_detail['data']['translation_value'];
}
}
}
return collect($translation);
});
if ($translation_data->isNotEmpty()) {
$single_translation_data = $translation_data->firstWhere('translation_keyword_key', $key);
if (check_valid_array($single_translation_data)) {
$translate_value = $single_translation_data['translation_value'];
$translate_default_value = $single_translation_data['translation_value'];
if ($translate_value != "") {
$translate = $translate_value;
} else {
$translate = $translate_default_value;
}
}
}
return $translate;
}
}
Try also adding"
\Illuminate\Session\Middleware\AuthenticateSession::class,
@jlrdw i tried but its not working i pasted code below u can see, when i try to access session in this file app/bootstrap.php given null
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Support\Str;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
apiPrefix:'api'
)
->withMiddleware(function (Middleware $middleware) {
$middleware->web(append: [
\App\Http\Middleware\IdentifyTenant::class,
\App\Http\Middleware\HandleInertiaRequests::class,
\Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class,
\App\Http\Middleware\SetLocale::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
// \App\Http\Middleware\CheckUserSession::class,
// \App\Http\Middleware\CheckAuthSession::class
]);
// $middleware->throttleWithRedis();
$middleware->alias([
// 'check_auth_session' => \App\Http\Middleware\CheckAuthSession::class,
// 'check_user_session' => \App\Http\Middleware\CheckUserSession::class,
]);
//
})
->withExceptions(function (Exceptions $exceptions) {
$exceptions->renderable(function (HttpException $exception) {
dd(session('UserData'));
$statusCode = $exception->getStatusCode();
$message = $exception->getMessage();
$translated_message = translation_front(Str::slug($message, '_'));
if ($statusCode == 404) {
$translated_message = translation_front('the_route_dashboardd_could_not_be_found');
}
return response()->view('errors.default', [
'status' => $statusCode,
'message' =>$translated_message ,
], $statusCode);
});
})->create();
Where are you defining the translation_front function and how are you loading it?
Bootstrap.php is the starting point of the app. When it's run, any helper functions or the session have not been loaded yet. It shouldn't be an issue if you're using it within exception callbacks since at that point the framework has been bootstrapped.
But note that session does not always exist. If you're running an artisan command, scheduled or queued job, or an API route call, there is no session.
@JussiMannisto how i translate my error pages like 404 and 419 and all error page dynamically
@saliem3651 You didn't say where you're defining the function or loading it.
Why are you appending the StartSession and VerifyCsrfToken middlewares? They're already in the web middleware stack by default. I'm not sure if adding them like this messes the order in which middlewares are executed. If it does, that's the issue. StartSession must be run before SetLocale, otherwise session data won't be loaded when you're trying to access it.
You should remove those two middlewares. If your VerifyCsrfToken class only has exceptions for URIs, you can define them dynamically instead:
$middleware->validateCsrfTokens(except: [
'some-url/*',
]);
But if your VerifyCsrfToken is more customized, you can replace the default CSRF middleware:
$middleware->web(replace: [
\Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class => \App\Http\Middleware\VerifyCsrfToken::class,
]);
<offTopicRant>
I dislike these changes in Laravel 11. In the old Kernel.php everything was explicit, you could jump to the parent class in one click and find every definition easily. The information is still there somewhere but it's harder to find. Like does the framework use a middleware priority list like it used to? No idea.
</offTopicRant>
@JussiMannisto i want just simple things i want i want if i change my language i want any error page it should be translated like 404,419 etc.....
@saliem3651 Why have you added those middlewares? Like I said, they might be the root of the issue.
If you try to access the session BEFORE it's loaded, it's not going to work.
@JussiMannisto i just removed the unwanted middleware
@saliem3651 And does it work?
@JussiMannisto no it does'nt worked for me
@saliem3651 Can you show your SetLocale middleware?
The issue is most likely that your middleware is being executed in the wrong order. To set the locale, you likely need access to the session. That means StartSession has to be run before SetLocale, and ValidateCsrfToken has to be run after them. Otherwise it will throw an exception before SetLocale is reached.
You might have to manually modify the order in which they are executed:
$middleware->priority([
\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\SetLocale::class,
\Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
]);
(Things were a lot more transparent before Laravel 11. You could see the middleware groups in Kernel.php and manually edit the order.)
@JussiMannisto i added what u given me
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Support\Str;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
apiPrefix:'api'
)
->withMiddleware(function (Middleware $middleware) {
$middleware->web(append: [
\App\Http\Middleware\IdentifyTenant::class,
\App\Http\Middleware\HandleInertiaRequests::class,
\Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
]);
$middleware->priority([
\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\SetLocale::class,
\Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
]);
// $middleware->throttleWithRedis();
})
->withExceptions(function (Exceptions $exceptions) {
$exceptions->renderable(function (HttpException $exception) {
$statusCode = $exception->getStatusCode();
$message = $exception->getMessage();
$translated_message = translation_front(Str::slug($message, '_'));
dd(translation_front('the_route_dashboardd_could_not_be_found'));
if ($statusCode == 404) {
$translated_message = translation_front('the_route_dashboardd_could_not_be_found');
}
return response()->view('errors.default', [
'status' => $statusCode,
'message' =>$translated_message ,
], $statusCode);
});
})->create();
`````` but still not working
@saliem Show the SetLocale middleware.
And what does "not working" mean? What are you doing, and what happens when you do it?
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Session;
use Illuminate\Support\Facades\App;
class SetLocale
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
if (Session::has('locale')) {
$locale = Session::get('locale');
App::setLocale($locale);
}
return $next($request);
}
}
`````` so this is my setlocale middleware
and this is my language list which is coming from another server
function get_language_master() { $datas = []; $datas = Cache::remember('get_language_master', 86400, function () { $data = []; $right_cat_detail = curl_request( config('constant.GET_LANGUAGE_LISTS'), [ 'translation_language_id' => 1, 'api_key' => config('constant.MASTER_API_KEY'), ] ); if (check_valid_array($right_cat_detail)) { if ($right_cat_detail['success_code'] == 1) { if (check_valid_array($right_cat_detail['data'])) { $data = $right_cat_detail['data']['translation_language_master']; } } } return $data; });
return $datas;
}
and this is my method which convert my translation key
if (!function_exists('translation_front')) { function translation_front($key) { $translate = '-'; $lang = 1; $language = 'en'; if (session()->has('locale')) { $language = Session::get('locale'); } $all_lang = collect(get_language_master()); $item = $all_lang->firstWhere('translation_language_short_form', $language); if ($item) { $lang = $item['translation_language_id'] ?? 0; }
$translation_data = Cache::remember('translation_front-' . $lang, 86400, function () use ($lang) {
$translation = [];
$lang_detail = curl_request(
config('constant.GET_TRANS_ALL_LIST'),
[
'translation_language_id' => $lang,
'api_key' => config('constant.MASTER_API_KEY')
]
);
if (check_valid_array($lang_detail)) {
if ($lang_detail['success_code'] == 1) {
if (check_valid_array($lang_detail['data'])) {
$translation = $lang_detail['data']['translation_value'];
}
}
}
return collect($translation);
});
if ($translation_data->isNotEmpty()) {
$single_translation_data = $translation_data->firstWhere('translation_keyword_key', $key);
if (check_valid_array($single_translation_data)) {
$translate_value = $single_translation_data['translation_value'];
$translate_default_value = $single_translation_data['translation_value'];
if ($translate_value != "") {
$translate = $translate_value;
} else {
$translate = $translate_default_value;
}
}
}
return $translate;
}
}
Please or to participate in this conversation.