Laravel set global Variable in middleware, all controller and views

Question: How to set and use global variable in Laravel? In this tutorial, we will learn how to set global Variable in middleware, all controller and views in laravel 5/6/7 application. you can set and get constants variable with class value, string value, Boolean Type value, date, integer value, array value and you can access for all controller, all views, all blade layouts files, middleware too in laravel 5/6/7 using config or class.

3 Ways to Get & Set Laravel global Variable

In this example we will create one global config file will all set & get default variable with values. so you can use that variable from anywhere in your project. you can also check bellow config/global.php for file location. Bellow is sample file for config File.

config/global.php

 '5.8',
    'website_type' => ['eCommerce', 'Business', 'Entertainment', 'Portfolio', 'Media', 'Brochure'],
    'role_list' => ['Media Manager', 'Designer', 'Developer', 'Manager', 'Business Manager', 'Other'],

    'admin_email' => 'admin_email@domain_name.extentions',
    'email_from_name' => 'YOUR Comany Name',
    'notification_email_main' => 'notification_email_main@domain_name.extentions',
    'notification_email' => 'notification@domain_name.extentions',
    'transactions_email' => 'transactions@domain_name.extentions',
    'info_email' => 'info@domain_name.extentions',
];

Laravel Middleware return variable to controller

accroding to me, the correct way to do this (in Laravel 5.x version) is to add your usage user define fields to the attributes property like as a pageTitle.

From the PHP source code messages, we can see attributes is used for usage parameters:

 /**
 * Custom parameters.
 *
 * @var \Symfony\Component\HttpFoundation\ParameterBag
 *
 * @api
 */
public $attributes;

So you would perform this as bellow variable for request;

$request->attributes->add(['website_name' => 'www.tamilrokers.com']);

You can then fetch the attribute by calling bellow example:

\Request::get('website_name');

Or from Get a request object in laravel 5.5+ versions using variable request object

 $request->get('website_name');

In laravel >= 5 versions,so you can use simply $request->merge in the middleware Based: using variable for request

public function handle($request, Closure $next)
{

    $request->merge(array("website_name" => "www.tamilrokers.com"));

    return $next($request);
}

And in the controller:
Set and Get Global Variable accessible in all controller functions on Laravel

public function index(Request $request)
{

    $website_name = $request->instance()->query('website_name');
    ...
}

Define Global Variable in Laravel

We must be require to set & get some global value for your PHP Based application such number of orders, website type, site url etc. if you are working with small project then i will suggest to create global config file for set & get constants variable.

Create Global Config File

We need to simple make a global.php config file with constants define a variable value as well as you can also define any types of the string data, true or false, yes or no, integer value, array value like as bellow:
config/global.php

 10,
    'website_type' => ['eCommerce', 'Business', 'Entertainment', 'Portfolio', 'Media', 'Brochure'],
]
?>

Use Global Variable

You can simply get & defing value using config() helper. you can see bellow example:
routes/web.php

Route::get('get-website-type', function()
{
    dd(config('global.website_type'));
});
Route::get('get-website-type', function()
{
    dd(config('global.total_orders'));
});

set global view variables using composer or view share

There so lots of the ways in website which is usual in every static or dynamic web page as well as you required to set them as global variable to share or allocate with every web pages.

For example, Every website has their SEO friendly dynamically Title Tag, comapny logo, Banner and some of great footer social Media information which is shared in every web pages.

In Laravel projects, you can simply set them in AppServiceProvider either using composer() method or share() method.

Here, We will see you how to set global variable and how to use them in your blade layouts file.

This is very helpful to set some usual variable as global because you can use them from anywhere in your blade layouts file.

You required to open your AppServiceProvider.php file as well as put bellow line of source PHP code to share or define variable in all views file.

app/Providers/AppServiceProvider.php

share('websiteName', 'Pakainfo.com');
       
    }
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

You can use all views composer() function to set or define global variable equivalent you define using share() function.

composer('*', function ($view) {
            $view->with('websiteName', 'Pakainfo.com');
        });
    }
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

And Last, you can use SEO friendly dynamically Title Tag “websiteName” get a variable in your every view blade layouts file :

{{ $websiteName }}

*Note: All blade layouts file view composers are resolved through the service container, therefor you may best solutions any dependencies you required within a global composer’s constructor.

Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Laravel global Variable.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment