Home > Net >  Undefined variable X issue when trying to display value on laravel blade
Undefined variable X issue when trying to display value on laravel blade

Time:12-01

I'm trying to follow a small laravel tutorial.

In my application I have a controller called, HomeController.

In my HomeController, I have the followinf index function

public function index()
    {
        try {
            //get autheticated users selected organisation
            $organisation = $this->getSelectedOrganisationByUser(Auth::user());

            //set application timezone
            $this->setApplicationTimezone($organisation);

            $this->setSiteConnection($organisation);
            $this->setGAConnection($organisation);

            if ($organisation->disabled) {
                Auth::logout();
                return redirect(route('login'));
            }
            //sales today
            $sum='23';
            return view('dashboard.index')
                ->with('organisation',$organisation,'sum',$sum);
        } catch (\Throwable $exception) {
            \Sentry\captureException($exception);
        }
    }

Here I'm trying to send this $sum value to my blade and display it. But, Every time i tried to display this value on my blade I get $sum is undefined error.

I tried to echo this on my blade as follows,

{{ $sum }}

What changes should I make, in order to display that on my blade.

I tried hard, but yet to figure out a solution

CodePudding user response:

You need to pass the variables as array. Try this:

return view('dashboard.index', ['organisation' => $organisation, 'sum' => $sum]);

CodePudding user response:

The method with() from /Illuminate/View/View.php accepts only two parameters.

To send multiple variable, you can

//Call with() for each variable
return view('dashboard.index')
                ->with('organisation',$organisation)
                ->with('sum',$sum);
//use an array as second parameter of view
return view('dashboard.index', ['organisation' => $organisation,'sum' => $sum]);
//use compact to create the array using the variable name
return view('dashboard.index', compact('organisation', 'sum'));
//use an array as first parameter in with (using compact or not)
return view('dashboard.index')->with(compact('organisation', 'sum'));
  • Related