Laravel print array in blade php

Viewed 126124

I want to show an array in my .blade.php, but it does not work properly so my controller looks like this:

class WatchController extends Controller
{

    public function index()
    {
        $watchFolderPath = 'C:\\xampp\\htdocs\\Pro\\rec\\';
        $watchFolder     = $this->dirToArray($watchFolderPath);
        return view('watch.new')->with('watchFolder', $watchFolder);
    }

    # Get Directories of Path as Array
    function dirToArray($dir) {

        $result = array();

        $cdir = scandir($dir);

        foreach ($cdir as $key => $value)
        {
            if (!in_array($value,array(".","..")))
            {
                if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
                {
                    $result[$value] = $this->dirToArray($dir . DIRECTORY_SEPARATOR . $value);
                }
                else
                {
                    $result[] = $value;
                }
            }
        }
        return $result;
    }
}

And inside my blade I just tried to call it like this:

{{ $watchFolder }}

but it did not work, I get the following error:

htmlentities() expects parameter 1 to be string, array given

Edit: The array I get shows all Folders/Files with subfolder in a directory. (used dd())

Currently it looks like this:

array:6 [▼
  123123 => array:2 [▼
    "subfolder1" => array:1 [▼
      0 => "video.mpg"
    ]
    "subfolder2" => array:1 [▶]
  ]
  789 => array:2 [▶]
  "folder1" => array:2 [▶]
  "folder2" => array:2 [▶]
  "folder3" => array:2 [▶]
  "folder1" => []
]
6 Answers

For those that might come looking...like me

echo implode("\n",$array);

else if its multidimensional array

echo implode("\n",array_collapse($array));

To output your $watchFolder array in a blade file, you can use the following method:

<pre><code>{{ json_encode($watchFolder, JSON_PRETTY_PRINT) }}</code></pre>

This will display a nicely formatted JSON version of your array and make it more readable:

{
    "123123": {
        "subfolder1": [
            "video.mpg"
        ],
        "subfolder2": []
    },
    "789": [],
    "folder1": [],
    "folder2": [],
    "folder3": []
}

You can also remove the JSON_PRETTY_PRINT if you only need to display it in a single line:

{"123123":{"subfolder1":["video.mpg"],"subfolder2":[]},"789":[],"folder1":[],"folder2":[],"folder3":[]}
Related