Brand3000's avatar

config() helper in bootstrap/app.php

Hi there! Upon developing each project, I have the config file for each specific project. For example config/laravel.php. I store different settings for each project. For example:

return [
    'cartKey' => 'laravel_cart',
];

Throughout the whole project I use config('laravel.cartKey)`. But this approach doesn't work in the bootstrap/app.php like so:

$middleware->encryptCookies(except: [
    config('laravel.cartKey`),
]);

Let me know if I'm wrong in my speculations or how to work in my case? Thanks.

0 likes
5 replies
martinbean's avatar

@brand3000 You‘re executing that code in a callback as part of the ApplicationBuilder class. Therefore it’s probably being called before the core framework service providers have ran, including the one for configuration.

puklipo's avatar
puklipo
Best Answer
Level 9

Use booted().

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })
    ->booted(function (Application $app) {
        EncryptCookies::except(config('...'));
    })->create();
1 like
RomainB's avatar

Somewhere in the Laravel documentation:

->withMiddleware(function (Middleware $middleware) {
    $middleware->trustHosts(at: fn () => config('app.trusted_hosts'));
})

Meaning you can use closure to delay the evaluation of the value.

I guess most of the place where you would need it is covered by this trick.

Please or to participate in this conversation.