0

i have a homeController function , I would like to pass multiple variables from this controller function to all views, not just the welcome view

class HomeStatsController extends Controller
{
    public function datacases()
    {
        // $malades=DB::table('stats')->first();
        // $malades = DB::table('stats')->where('date', '=', DATE(now()));
        $maj =   DB::table('stats')->orderBy('id', 'desc')->value('created_at');
        $malades =   DB::table('stats')->whereDate('date', \Carbon\Carbon::today())->get()->sum('nbrmal');
        $guerris= DB::table('stats')->whereDate('date', \Carbon\Carbon::today())->get()->sum('nbrgue');
        $morts = DB::table('stats')->whereDate('date', \Carbon\Carbon::today())->get()->sum('nbrmort');
        $maladestotal =   DB::table('stats')->get()->sum('nbrmal');
        $guerristotal = DB::table('stats')->sum('nbrgue');
        $mortstotal = DB::table('stats')->sum('nbrmort');
        $publications =   DB::table('informations')->orderBy('created_at', 'desc')->limit(3)->get();
        
        return view('welcome',compact('malades','maj','guerris','morts', 'maladestotal', 'guerristotal', 'mortstotal','publications'));
    } }

  • This is exactly what you want: https://laravel.com/docs/8.x/views#sharing-data-with-all-views – Kevin Bui Sep 14 '20 at 01:49
  • Does this answer your question? [Pass variables to multiple view in laravel](https://stackoverflow.com/questions/51845725/pass-variables-to-multiple-view-in-laravel) – Hamid Ali Sep 14 '20 at 06:39

1 Answers1

0

the easy way to share variable to all views is

<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->share('key','value');
    }
}

but if you want share to specific views use (view composers)

https://laravel.com/docs/6.x/views#view-composers

  • can I copy the sql request as it is in the boot function? for example : $guerris= DB::table('stats')->whereDate('date', \Carbon\Carbon::today())->get()->sum('nbrgue'); I can put the variable: as it is written? because it is not a simple select All from the table as I found in the other tutorials – Lamia Medj Sep 14 '20 at 14:57
  • finally I was able to write a whole sql request in the boot function, I just imported: use Illuminate\Support\Facades\DB; – Lamia Medj Sep 14 '20 at 17:31