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

<?php
return [
    'application_version' => '5.8',
    'website_type' => ['eCommerce', 'Business', 'Entertainment', 'Portfolio', 'Media', 'Brochure'],
    'role_list' => ['Media Manager', 'Designer', 'Developer', 'Manager', 'Business Manager', 'Other'],

    'admin_email' => '[email protected]_name.extentions',
    'email_from_name' => 'YOUR Comany Name',
    'notification_email_main' => '[email protected]_name.extentions',
    'notification_email' => '[email protected]_name.extentions',
    'transactions_email' => '[email protected]_name.extentions',
    'info_email' => '[email protected]_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.

Read Also:  laravel search multiple tables Example

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

<?php
return [
    'total_orders' => 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.

Read Also:  Laravel Global Variables Example Tutorial From Scratch

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.

Read Also:  convert date format in php

app/Providers/AppServiceProvider.php

<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->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.

<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        
        view()->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.


Related FAQ

Here are some more FAQ related to this Article:

  1. Read Also:  How to Declare Global Variable in Laravel 6?
  2. Read Also:  Creating dynamic Add Remove rows table with Vuejs
  3. Read Also:  ANGULARJS PHP MySQL Inline CRUD Example Tutorial From Scratch
  4. Read Also:  Global Config variable In Laravel 6 Example
  5. Read Also:  laravel 5.8 global constants variable
  6. Read Also:  Laravel Define Global constants Config variables value
  7. Read Also:  JQuery Sortable elements using drag and drop
  8. Read Also:  Global variable in laravel controller Example
  9. Read Also:  Email Verification in Laravel 5.7 Example Tutorial
  10. Read Also:  jquery radio button selected event
CLOSEX