Jawad
Jawad

Reputation: 87

How to set Global variable in Laravel?

I am trying to set a global variable in Laravel, I set in __construct() function but can not use this outside of controller. Where should I set that variable?

public function __construct()
{
    $cat = Categories::get()->first();
}

but I can't access the $cat variable in some pages.

Upvotes: 6

Views: 19746

Answers (3)

ztvmark
ztvmark

Reputation: 1434

Use service providers

https://hdtuto.com/article/laravel-5-global-variable-in-all-views-file

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('siteTitle', 'HDTuto.com');



    }

    /**

     * Register any application services.

     *

     * @return void

     */

    public function register()

    {

        //

    }

}

and in your view

{{ $siteTitle }}

Upvotes: 6

Dilip Patel
Dilip Patel

Reputation: 822

You may also use solution, which is as given below:

App::before(function($request) {
    App::singleton('cat', function(){
        return Categories::get()->first();
    });
});

Now to get data in controller using below line;

$cat = app('cat');

and you can pass data in view using below line:

view('home', compact('cat'));

Upvotes: 2

Iftikhar uddin
Iftikhar uddin

Reputation: 3182

If you want to access $cat variable everywhere i.e in all controllers and views you should share it as below:

protected $cat;

public function __construct()
{
    $this->cat = Categories::get()->first();
    View::share('site_settings', $this->cat);
}

I will assume that you are using BaseController constructor. Now if your controllers extend this BaseController, they can just access the category using $this->cat.

Second Method:

You can also give a try using Config class. All you need to do is add the following code within boot method of app/Providers/AppServiceProvider.php

Config::set(['user' => ['name' => 'John Doe']]);

Then any where in your project you can fetch the value by using Config::get('user.name');

Upvotes: 6

Related Questions