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'));
    } }

2

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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
finally I was able to write a whole sql request in the boot function, I just imported: use Illuminate\Support\Facades\DB;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.