Laravel 5.6 - global and dynamic variable

0

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

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

  • I initially tried config, but it did not work;
  • I tried to use Session, but I had the same problem;
  • I tried to set a variable in the "super controller", where all the controllers extended to it, it did not work.
  • The value of the variable is only valid during the execution of the request, ie, I make a request to the controller aaaControler, this makes use of other controllers, within the same request the value persists, but ends in the return. >

    I thought of persisting in the database, creating a reference and always fetching this value there, but will this be the best way?

    I ask for help with this question.

    Thank you.

        
    asked by anonymous 27.11.2018 / 17:31

    1 answer

    0

    You can do this using view composer . The view composer runs when the view is loaded, so you can pass in Closure with additional functionality for a particular view.

    To determine a composer for all views use the wildcard * ;

    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. However, laravél also has view creators , which is executed when a view is instantiated.

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

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

    You can still use view share.

        
    27.11.2018 / 17:46