5

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.

Ariful Islam
  • 7,639
  • 7
  • 36
  • 54
Jawad
  • 77
  • 1
  • 2
  • 8
  • 1
    Do you want to be able to access `$cat` across views? – Mozammil Jan 20 '19 at 07:09
  • You may check this answer: [global variable for all controller and views](https://stackoverflow.com/questions/25189427/global-variable-for-all-controller-and-views) – user2682025 Jan 20 '19 at 07:10
  • You may want to look at Laravel's View Composers to share data across all views. (https://laravel.com/docs/master/views#view-composers) – Matt Wohler Jan 20 '19 at 07:24

3 Answers3

6

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');

Iftikhar uddin
  • 3,117
  • 3
  • 29
  • 48
6

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 }}
ztvmark
  • 1,319
  • 15
  • 11
1

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'));
Iftikhar uddin
  • 3,117
  • 3
  • 29
  • 48
Dilip Patel
  • 764
  • 15
  • 24