Global variable in laravel controller Example

Today, We want to share with you Global variable in laravel controller.In this post we will show you laravel set global variable in middleware, hear for How to Define Global Variable in Laravel 5.8 Application we will give you demo and example for implement.In this post, we will learn about How to create a variable accessible to all controllers and views? with an example.

Global variable in laravel controller

There are the Following The simple About Laravel 6 Global Variable for All Controller and Views Full Information With Example and source code.

As I will cover this Post with live Working example to develop laravel global constants, so the define variable in constructor laravel is used for this example is following below.

Global variable in laravel controller

Use the AppServiceProvider

In this case $created_year is available to ALL Page Blade file views!

namespace App\Providers;

use Carbon;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        view()->share('created_year', Carbon::parse()->year);
    }

    public function register()
    {
        //
    }
}

Use a View Composer

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Carbon;

class ComposerServiceProvider extends ServiceProvider
{
    public function boot()
    {
        view()->composer('products.*', function ($view) {
            $view->with('created_year', Carbon::parse()->year);
        });
    }

    public function register()
    {
        //
    }
}

3. Use Blades @inject-method

@inject('carbon', 'Carbon\Carbon')

{{ $carbon->parse()->year }}
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 global variable in view laravel 6.2.
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