php – global variable in laravel-ThrowExceptions

Exception or error:

In PHP, I used to define some variables in my header.php and use them in all my pages. How can I have something like that in Laravel?

I am not talking about View::share('xx', 'xx' );

Assume I want to have a variable which holds a number in it and I need this number inside all my controllers to calculate something.

How to solve:

Sounds like a good candidate for a configuration file.

Create a new one, let’s call it calculations.php:

Laravel ~4ish:

app
    config
        calculations.php

Laravel 5,6,7+:

config
    calculations.php

Then put stuff in the new config file:

<?php return [ 'some_key' => 42 ];

Then retrieve the config in your code somewhere (note the file name becomes a “namespace” of sorts for the config item):

echo Config::get('calculations.some_key'); // 42 in Laravel ~4
echo config('calculations.some_key'); // 42 in Laravel ~5,6,7+

Answer:

Set a property on the BaseController, which should be located in your controllers directory.

Your controllers should extend the BaseController class and thus inherit its properties.

Answer:

You could use View Composers

And instead of using the boot method described in the docs you could use:

public function boot()
{
    // Using class based composers...
    view()->composer(
        '*', 'App\Http\ViewComposers\ProfileComposer'
    );

    // Using Closure based composers...
    view()->composer('*', function ($view) {

    });
}

That would render whatever variables you declare with

$view->with('yourVariableName', 'yourVariableValue');

to all the views in your app.

Here is a full example of how I used this in one of my projects.

app/Providers/ComposerServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
     /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer(
            '*', 'App\Http\ViewComposers\UserComposer'
        );
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

app/Http/ViewComposers/UserComposer.php

<?php

namespace App\Http\ViewComposers;

use Illuminate\Contracts\View\View;
use Illuminate\Contracts\Auth\Guard;

class UserComposer
{

    protected $auth;

    public function __construct(Guard $auth)
    {
        // Dependencies automatically resolved by service container...
        $this->auth = $auth;
    }

    public function compose(View $view)
    {
        $view->with('loggedInUser', $this->auth->user());
    }
}

Just remember that because you declared a new service provider it needs to be included in the ‘providers’ array in config/app.php

Leave a Reply

Your email address will not be published. Required fields are marked *