Accessing Laravel .env variables in blade - php

I am trying to get some API keys which I have stored in my .env file to use in the blade javascript. I have added two keys like:
APP_ENV=local
APP_KEY=////
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost
APP_GOOGLE_MAPS=////
APP_OVERHEID_IO=////
In blade I need to use the Google Maps API and OverheidIO API key. I have tried getting one of the default .env variables just in case I have formatted the custom .env variables wrong.:
{{ env('APP.ENV') }} // nothing
{{ env('APP_ENV') }} // nothing
{{ env('APP_ENV'), 'test' }} // returns 'test'
Could someone help me call the google maps api and overheidio api key in the blade?

Five most important commands if your Laravel is not working as expected after some modifications in .env or database folder or because of any other modifications.
Here is full explanation:
https://www.youtube.com/watch?v=Q1ynDMC8UGg
php artisan config:clear
php artisan cache:clear
composer dump-autoload
php artisan view:clear
php artisan route:clear

VERY IMPORTANT
All env() like: env('APP_ENV') calls WON'T WORK in production (when you use php artisan config:cache)
What to use?
use env() only in config files
use App::environment() for checking the environment (APP_ENV in .env).
use config('app.var') for all other env variables, ex. config('app.debug')
create own config files for your own ENV variables. Example:
In your .env:
MY_VALUE=foo
example config/myconfig.php
return [
'myvalue' => env('MY_VALUE', 'bar'), // 'bar' is default if MY_VALUE is missing in .env
];
Access in your code:
config('myconfig.myvalue') // will result in 'foo'
More details see HERE

I have it implemented in the following way:
#if (env('APP_ENV')!='Production')
Enviroment Test
#endif
My recommendation is to execute the following command: composer self-update

You should only access .env values directly inside configuration files, then access them from everywhere (controllers, views) from configuration files using config() helper
For example:
.env
TEST_URL=http://test
config/app.php
return [
'test_url' => env('TEST_URL','http://default.url')
];
resources/views/welcome.blade.php
{{ config('app.test_url')}}
see configuration caching from laravel documentation for more info.

If you want to get the environment of the app then try this:
{{App::environment()}}
I have not tried other variables.

Since Laravel 7.11, you can use the #env('') and #production() directives in blade templates:
#env('staging')
// The application is running in "staging"...
#endenv
#env(['staging', 'production'])
// The application is running in "staging" or "production"...
#endenv
or
#production
// Production specific content...
#endproduction
See also in the Laravel Blade Documentation.

php artisan config:clear
should fix it

It causes problems to use env() anywhere else than in the config/ folder. Use env in there and then config () in the other parts of the app

get values here: config/app.php
in blade:
{{ config('app.name', 'default value here') }}
in class/controller:
config('app.name', 'default value here')

Here's a link to the documentation: https://laravel.com/docs/6.x/configuration#retrieving-environment-configuration
In the sample below, I spit out the actual error when I'm in my development environment but give a generic message if in any other environment.
#if(App::environment('development'))
Error: {{ $record->s_error }}
#else
XML Parsing Error - Please double check that your file is formatted correctly.
#endif

{{ env('APP_ENV') }}
**If It doesn't work then run the below command. It worked for me. You can try. This command will clear the configuration cache. **
php artisan config:clear

Never use env() anywhere in your code, other than inside config/*.php
Use config() to access default/custom variables in blade files/Controllers.
For example
config('app.name')
config('app.env')
where app is the file name inside the config directory.
you can use any file name inside config directory to access the variable inside it.
Although answers by others are right, i found it hard to understand, so finally read the whole documentation for config page.
Important comment from documentation.
Once the configuration has been cached, the .env file will not be loaded; therefore, the env function will only return external, system level environment variables.

This command should be written after you edit .env file to access variables in easy way
php artisan config:cache

i was also having trouble getting value from .env file, then i did this and it helped :
Check env file and see if you have given the correct value.
then check blade or controller where you using that variable from .env file.
if both steps above goes right, you just need to do these steps -
php artisan config:clear
php artisan cache:clear
php artisan view:clear
php artisan route:clear
composer dump-autoload

Run the following command.
php artisan optimize

if (env('APP_ENV')=='Production')
do something login,verify etc
else
do something
Here env('APP_ENV') won't work in production so better to get from
config folder and make your own file and access that.
Ex:-config/customconfig.php ->make new file
env('APP_ENV'),
];
and then you can access like this
if (config('customconfig.appenv')=='Production')
do something login,verify etc
else
do something
and final run php artisan config:cache

Related

Laravel 9 - Vite is not bundling my images even if I declared the entry point

I am using Laravel 9.27.0
I am trying to reference an image directly on my master.blade.php located on resources/views. This image is being used as the favicon for the site I am working on. According to the documentation, I should be able to reference this image with Vite by adding the following to my app.js
import.meta.glob([
'../images/**'
]);
And I should be referencing the image in my blade using this code.
{{ Vite::asset('resources/images/favicon.png') }}
However I kept getting Unable to locate file in Vite manifest: resources/images/favicon.png.
Am I misunderstanding this or am I doing something wrong?
You have to follow this:
https://laravel.com/docs/9.x/vite#working-with-blade-and-routes,
In resources/js/app.js you have to add
import.meta.glob([ '../images/**', ]);
and also in your config/app.php have facade alias defined:
'Vite' => \Illuminate\Support\Facades\Vite::class,
then you can use
<img src="{{ Vite::asset('resources/images/photo.jpg') }}" >
You could try also run command:
npm run build
That also will reload everything in Vite config.
The answer is here: https://stackoverflow.com/questions/73502963/larave-vite-vite-manifest-missing-odd-files
Need to add this in vite.config.js:
build: {
assetsInlineLimit: 0
}
I just had the same issue.
It was about read permissions on the images folder, as the web server was not permitted to access and read it.
I had the same problem, but I could solve it, deleting the file public/hot.
These steps I followed:
Set my image <img src="{{ Vite::asset('resources/img/image.png') }}" alt="image">
Add Vite alias in config/app.php file: 'Vite' => \Illuminate\Support\Facades\Vite::class,
Clear cached config php artisan config:clear
Run command npm run dev (This creates public/hot file).
Delete file public/hot.
Run command npm run build.

Laravel: how to cache config files properly

I'm using Laravel 8.0 in my application and I added a new .env variable:
APP_URL_FRONT=https://tmsv00008:6204
And how I use it:
To access the project use the following link: LINK
When I deploy the application I cache the config files:
php artisan config:cache
But the env files is not visible and the strange thing is that if I execute:
php artisan config:clear
The variable is visible.
What I'm doing wrong? Because it doesn't make sense to me.
Also, in this article they suggest to execute the commands in this order:
php artisan config:cache
php artisan config:clear
But this doesn't make sense to me. Shouldn't be the other way around? And I think the cache commands also clears the cache first.
The env() function is strongly recommended to be used only in configuration file, since caching the configurations, will make the env function to return null
In other words, crate a configuration file, with that environment variable, or add it to an existing one
It's hidden in an old update guide this "note"

Laravel not reading env variables from different env files

After upgrade from 5.0 to 5.8, laravel stopped reading env variables if the env is different than .env file.
For example, if i have .env file with the USE_SSL=true inside it.
env('USE_SSL') will be true
But if i have .env file pointing to another env:
APP_ENV=dev
and than i'll have .env.dev file containing USE_SSL=true , env('USE_SSL') will be null.
I tried composer dump-autoload and php artisan config:clear, and php artisan config:cache - no luck. cached or not, i can't get the value.
I tried naming the files .dev.env and .env.dev - no luck.
Any ideas would be appreciated.
I'm adding this as an answer, but please note this isn't how .env file should be used according to laravel docs. It's just a way i needed to use due to some restrictions which required me to use different config files for each env, and load it in runtime. For correct usage of .env file check the docs.
This is a way of loading different config files in runtime depends on where the APP_ENV is pointing. I'm marking this as answered since it's answering this specific question.
.env
APP_ENV=specific_domain
.env.specific_domain
USE_SSL=true
Http/Kernel.php
public function __construct(Application $app, Router $router)
{
parent::__construct($app, $router);
$app_env = explode("=", file($app->environmentFilePath(), FILE_IGNORE_NEW_LINES)[0])[1];
$app->loadEnvironmentFrom(".env.$app_env");
}
Alright if you really wanted to do this,
Route::get('renderEnvChaining',function(){
$myCustomEnv = parse_ini_file(base_path(env('CUSTOM_ENV')));
return $myCustomEnv['USE_SSL']; // This will return true
});
In my .env file i've mentioned this,
CUSTOM_ENV=.env.example
Now i in default env.example i put this
USE_SSL="true" // This will return true
USE_SSL=true // This will return 1
I just found that .ini and .env follows the same values, so i parsed .env file as .ini file,
Give this a try, i've never done this thing before, please concern with other developers before running this into production server

Laravel 5.5 APP_URL not changing

I am trying to change the path output of {{ url('images/image.png') }} and {{ asset('images/image.png') }} Based on my reading, it sounds like I just need to set APP_URL in my .env file and off we go. Well, unfortunately that is not the case. I have set APP_URL=http://localhost in my .env file. I also set 'url' => env('APP_URL', 'http://broken.af') in my config/app.php file. Additionally, I have also tried setting ASSET_URL in both locations with the same result. I have also run artisan cache:clear, artisan config:clear and artisan config:cache. I also tried restarting the server just to be extra sure. For some reason Laravel keeps using the servers configured hostname for these values.
Not a dupe, we are not talking about the route paths, we are talking about the url and asset function and APP_URL and ASSET_URL not doing anything.
I am going to go ahead and post the answer to my question. If UrlGenerator::forceRootUrl is not used, it will inevitably fallback to Request::root() which is implemented as follows: return rtrim($this->getSchemeAndHttpHost().$this->getBaseUrl(), '/');
I am not sure what ASSET_URL or SITE_URL do, if anything. These env variables are definitely not used in the url or asset functions. This does not appear to have changed in later versions of Laravel.
The only way I was able to find to get these variables to work was to manually read them in RouteServiceProvider::boot() and then call forceRootUrl.
public function boot()
{
parent::boot();
/** #var UrlGenerator $url */
$url = $this->app['url'];
// Force the application URL
$url->forceRootUrl(config('app.url'));
}
The trace:
https://github.com/illuminate/routing/blob/master/UrlGenerator.php#L204
https://github.com/illuminate/routing/blob/master/UrlGenerator.php#L492
https://github.com/illuminate/routing/blob/master/UrlGenerator.php#L494
https://github.com/illuminate/http/blob/master/Request.php#L89
As you are trying to get an asset, in your case it's an image it will be right to use asset() laravel helper,
for more information, please check laravel method-asset helper
If you have all your assets in the default public folder, use the Fully Qualified Domain Name (including security protocol) for your APP_URL in your .env file. Example:
APP_URL=https://broken.af
Also use the same for your config/app.php file:
'url' => env('APP_URL', 'https://broken.af'),
If this is helpful for someone, this code worked for me:
$url = env('APP_URL').Storage::url($file->path);
This is how I'm saving the file previously:
$file->path = $request->file("file")->store("public");
I found this answer here
p.d. Don't forget to do the symlink like documentation mention here
php artisan storage:link

Should I be using env() outside my config files?

I stumbled across this https://laravel.com/docs/5.4/configuration#configuration-caching in the documentation and it confused me a bit.
When I want an environment variable I use the env() function to return what I want. According to the above link it says I should be using the config() function instead to ensure that on production I am accessing the values through a cache.
e.g. These both return the same thing
env('APP_URL')
vs
config('app.url')
So should I be using config() or env() inside my app?
I assume that if I add a new env variable I will also need to update my config files?
You should never use env() in the code directly. It's a good practice to use config(). In config files use env() to get the data from .env file.
In this case, you can easily override config values at runtime or during testing.
You also can use config caching.
To give your application a speed boost, you should cache all of your configuration files into a single file using the config:cache Artisan command.
Another reason is described in the docs:
You should typically run the php artisan config:cache command as part of your production deployment routine. If you execute the config:cache command during your deployment process, you should be sure that you are only calling the env function from within your configuration files.

Categories