High 5.6 - global and dynamic variable

Asked

Viewed 1,411 times

1

I have an API with Laravel 5.6 and need to create global variables that throughout the application can have their value changed, but I’m having problems.

Example: 1. In the first request, the value of this variable as "test"; 2. In the second request I want to take the current value, which should be "test";

  1. I initially tried using config, but it didn’t work;
  2. I tried to use Session, but I had the same problem;
  3. I tried to set a variable in the "super controller", where all the controllers extend to it, it didn’t work.

The variable value is only valid during the execution of the request, that is, I make a request to the aaaControler controller, it makes use of other controllers, within the same request the value persists, but ends in the return.

I thought to persist in the database, create a reference and always search for this value there, but this will be the best way ?

I ask for help in this matter.

Thank you.

  • have tried using Composer?

  • Yes, you should persist the value, but not necessarily in the bank. In session it should already work, since it serves precisely for this. There are also other options, such as file persistence, memcached, redis, etc. To understand more what is happening, you should read about how the HTTP protocol is stateless. Start with What is a "stateless protocol", like HTTP?

1 answer

1

You can do using view Composer. The Composer view runs when the view is loaded, this way you can pass in a Closure with additional features for a particular view.

To determine a Composer for all views use the joker *;

View::composer('*', function($view)
{
    $view->with('variavel','Valor qualquer');
});

You can do this also without using Closures.

View::composer('*', 'App\Http\ViewComposers\ProfileComposer');

View Composers are executed when a view is rendered. But laravél also has view creators, that are executed when a view is instantiated.

You can also choose to use a BaseController with a"setupLayout" method. Therefore, all views that are loaded will be loaded by setupLayout, to which you will add the additional data you need.

However, using the Composers views, you will be sure that this part of the code will be executed. But using the BaseController, the flexibility is greater because you can avoid loading the extra data.

You can still use the view share.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.