Laravel sometimes error 500, SQLSTATE[HY000] [1045]
I’m trying to make application settings from the database, otherwise load from .env
How to make a request to the database in the service provider?
Sometimes there is no error, sometimes there is error 500 and there is no connection to the database.
AppServiceProvider.php
public function boot(): void
{
Schema::defaultStringLength(191);
Vite::useScriptTagAttributes(['async' => true]);
Blade::anonymousComponentPath(__DIR__.'/../../resources/views/admin/layout/components', 'admin');
Blade::anonymousComponentPath(__DIR__.'/../../resources/views/template/layout/components', 'template');
$namesVariables = [
'name',
'description',
'lang',
'timezone',
'telegram',
'url',
'admin_url',
];
foreach($namesVariables as $variable)
{
${'site_'.$variable} = Cache::get('site_'.$variable, '');
}
if (empty($site_name) && empty($site_description)
&& empty($site_lang)
&& empty($site_timezone)
&& empty($site_telegram)
&& empty($site_url)
&& empty($site_admin_url))
{
$settings = Setting::find(1);
if (!empty($settings))
{
foreach($namesVariables as $variable)
{
${'site_'.$variable} = $settings['site_'.$variable];
Cache::put('site_'.$variable, ${'site_'.$variable},
now()->addMinutes($this->cacheNum));
}
} else {
$site_name = env('APP_NAME');
$site_description = env('APP_DESCRIPTION');
$site_telegram = env('APP_TELEGRAM');
$site_url = env('APP_URL');
$site_admin_url = env('APP_ADMIN_URL');
Cache::put('site_name', $site_name,
now()->addMinutes($this->cacheNum));
Cache::put('site_description', $site_description,
now()->addMinutes($this->cacheNum));
Cache::put('site_telegram', $site_telegram,
now()->addMinutes($this->cacheNum));
Cache::put('site_url', $site_url,
now()->addMinutes($this->cacheNum));
Cache::put('site_admin_url', $site_admin_url,
now()->addMinutes($this->cacheNum));
}
}
Config::set('app.name', $site_name);
Config::set('app.site_description', $site_description);
App::setLocale($site_lang);
Config::set('app.timezone', $site_timezone);
Config::set('app.site_telegram', $site_telegram);
Config::set('app.url', $site_url);
Config::set('app.site_admin_url', $site_admin_url);
}
Log
Laravel log gives an error
[2024-08-03 09:40:00] production.ERROR: SQLSTATE[HY000] [1045] Access denied for user 'forge'@'localhost' (using password: YES) (Connection: mysql, SQL: select * from `settings` where `settings`.`id` = 1 limit 1) {"exception":"[object] (Illuminate\Database\QueryException(code: 1045): SQLSTATE[HY000] [1045] Access denied for user 'forge'@'localhost' (using password: YES) (Connection: mysql, SQL: select * from `settings` where `settings`.`id` = 1 limit 1) at D:\Web\laragon\www\mysite\vendor\laravel\framework\src\Illuminate\Database\Connection.php:829)
[stacktrace]
#0
$settings = Setting::find(1);
New contributor
vladneverov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.