1

Is it possible to share and change some variable between multiple views? For example, I want to have a variable $user that will be shared between all views. When a user logs the variable is set up, when the user logs out, the variable is unset. I was unable to achieve requested using the following combination: in AppServiceProvider:

view()->share('var', 1);

in the controller:

$var = view()->shared('var');.
$var ++;
view()->share('var', var);
return view(''', 'var'=>$var)

Every time when the page is reloaded $var is always the same (2).

2 Answers2

1

I want to have a variable $user that will be shared between all views

You should use auth()->user() to get authenticated user instance in any view.

But if you don't want to use it for some reason, you could share the variable between multiple views with a view composer.

share() method will be useful only if you want to share a variable with all views. To make it work, put view()->share('key', 'value') to the boot() method of a service provider.

Also, the code in your controller looks like you want to share data not between views, but between requests. Use session for that.

To save the data:

session(['key' => 'value']);

To get the data in another request:

session('key');
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • But why does my code doesn't behave as expected? Why isn't shared var incremented for 1 each time? – Djordje Zivanovic Jan 03 '18 at 18:06
  • @ЂорђеЖивановић you need to put `view()->share('key', 'value')` to the `boot()` method of a service provider and then use it in any view with `{{ $key }}` – Alexey Mezenin Jan 03 '18 at 18:07
  • As I stated in my comment: in AppServiceProvider: view()->share('var', 1); But I need to change that variable when a user logs in. – Djordje Zivanovic Jan 03 '18 at 18:08
  • 1
    @ЂорђеЖивановић it looks like you want to share the data between requests, use session for that. I've updated my answer. – Alexey Mezenin Jan 03 '18 at 18:10
1

It would be better to add another service provider. Take a look at my provider:

  <?php

     namespace App\Providers;

     use Request;
     use Illuminate\Support\ServiceProvider;


 class ViewComposerServiceProvider extends ServiceProvider
{
public function boot()
{

   $this->globalThings();
   //call another globals' function here
}

public function register()
{
    //
}

/**
 * Get the golbals
 */
private function globalThings()
{
    view()->composer(array('*.*'),function($view){
        //get the data however you want it!
        $view->with('global', Model::where('field','value')->get());
    });
}

And don't forget to add the service provider to list of provider is config/app.php

        App\Providers\ViewComposerServiceProvider::class,
Mahdi Younesi
  • 6,889
  • 2
  • 20
  • 51