conny
conny

Reputation: 119

Array can't pass to blade. What should I do?

I would like to pass an Array to blade template. but somehow the array always become null in blade. I don't where I should fix.

    public function stackover(Request $request)
    {
        $resultList = array();
        $dateListArray = $this->getChargeData($request->id);
        Log::debug($dateListArray);
        foreach($dateListArray as $datelist)
        {
            array_push($resultList,$datelist);
        }
        Log::debug("CHARGELIST");
        Log::debug($resultList);
        return view('stacker',compact($resultList));
    }

in blade.php

  console.log({{$resultList ?? ''}});

data becomes empty.

Log::debug("CHARGELIST");
Log::debug($chargeList);

The result is here

 array (
  0 => 
  (object) array(
     'delivery_date' => '2021-08-03 00:00:00',
     'amount' => 10000,
     'cost' => 0,
  ),
  1 => 
  (object) array(
     'delivery_date' => '2021-08-06 00:00:00',
     'amount' => 400,
     'shipping_cost' => 1100,
  ),
  2 => 
  (object) array(
     'delivery_date' => '2021-08-13 00:00:00',
     'amount' => 1100,
     'cost' => 1100,
  ),
)  

Upvotes: 0

Views: 155

Answers (2)

Tayyab mehar
Tayyab mehar

Reputation: 621

You can have alternates to get the array in the blade.

return View::make('stacker',$resultList);

The compact() function is used to convert a given variable to an array in which the key of the array will be the name of the variable and the value of the array will be the value of the variable.

return view('stacker',compact('resultList'));

If you already have the array you can pass it with the with() function.

 return view('stacker')->with($resultList);

Upvotes: 2

Yves Kipondo
Yves Kipondo

Reputation: 5603

The issue is due to the fact that your are passing the $resultList variable as value to the compact function instead of the name of the variable as a string`

return view('stacker',compact($resultList));

You should fix that by changing the above line like this

return view('stacker',compact('resultList'));

Upvotes: 3

Related Questions