1

I would like assistance with calling a global variable on Laravel app for specific pages or routes.

This is my current code which works on login

App\Providers\AppServiceProvider

public function boot()
{
   view()->composer(['auth.login'], function ($view) {
      $view->with('settings', AppSetting::where('id',1)->first());
   });
}

This is the route for the login page

Route::get('/', function () {
    return view('auth.login');
});

[Edit 1]

On the login page , I used this code bellow to get the app version

{{$settings->app_version}}

example

loic.lopez
  • 2,013
  • 2
  • 21
  • 42
  • which global variable you want use? – loic.lopez Feb 08 '20 at 17:44
  • On my login blade view , I am using ```{{$settings->app_version}}``` to show the app name from saved db values which are on **app_settings** table. Initially, I had ``` view()->composer('*', function ($view) { $view->with('settings', AppSetting::where('id',1)->first()); }); ``` Which was loading everywhere but that is giving me too many duplicate queries in some areas where I have many models in on Controller. So, I want it to be only available on specific views or models. – Bongani Napoleon Dlamini Feb 08 '20 at 18:42
  • try to clarify your question by adding an example – loic.lopez Feb 08 '20 at 19:13
  • why do you need to store your version in database? – loic.lopez Feb 09 '20 at 11:29

1 Answers1

0

After digging a little I think a good solution might be caching your AppSetting Model.

Write the given code in App\Providers\RouteServiceProvider

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{


   /**
   * Define your route model bindings, pattern filters, etc.
   *
   * @return void
   */
   public function boot()
   {
      parent::boot();
      App::before(function($request) {
           App::singleton('settings', function(){
             return AppSetting::where('id',1)->first();
           });

       // If you use this line of code then it'll be available in any view
       // as $settings but you may also use app('settings') as well
       View::share('settings', app('settings'));
     });
   }
}

App::singleton will call once AppSetting::where('id',1)->first() and after one call your settings will be cached.

And you can use {{$settings->app_version}} in your view.

Reference: stackoverflow.com/a/25190686/7047493

loic.lopez
  • 2,013
  • 2
  • 21
  • 42