2

I have products in a database that are essentially used on every single page. Instead of having to query the database, something like this:

$products = DB::table("products")->get();

And then passing it into view:

return view("site.products", array(
   'products' => $products,
)); 

I don't want to do this for every view. Instead, I want $products to be available to ALL templates by default... so that I can do this:

@foreach ($products as $product) 
 ... etc

How would I declare it in a global way to achieve this?

rockstardev
  • 13,479
  • 39
  • 164
  • 296

2 Answers2

2

You can add below code in the boot method of AppServiceProvider

public function boot()
{
    if (!$this->app->runningInConsole()) {
        $products = DB::table("products")->get();
        \View::share('products', $products);
    }
}

Read more from here

SEYED BABAK ASHRAFI
  • 4,093
  • 4
  • 22
  • 32
1

A recommended way of doing this is to add a middleware that you apply to all the routes that you want to affect.

Middleware

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\View;

class GlobalVariablesMiddleware
{
    $myVariable = "Value For Everyone";
    View::share(['globalValue' => $myVariable]);
}

Add it to your kernel.php in the Http folder

protected $routeMiddleware = [
        ...
        'myMiddleware' => \App\Http\Middleware\ GlobalVariablesMiddleware::class,
];

Once this is setup, you can easily apply it to individual routes or grouped ones to achieve what you are looking for

// Routes that will have the middleware    
Route::middleware(['myMiddleware'])->group(function () {
    
        // My first route that will have the global value
        Route::resource('/profile', App\Http\Controllers\ProfileController::class);

        // My second route that will have the global value
        Route::resource('/posts', App\Http\Controllers\PostController::class);
    });

By doing it this way, you can easily control the data in the future if you would chose not to have the data global.

Eric Qvarnström
  • 779
  • 6
  • 21