Tylerlee12 Tylerlee12 - 1 year ago 116
PHP Question

PHP scandir failing in Laravel

So I'm trying to pass a directory to a model function in my Laravel application that uses PHP's

, and it can't seem to find the directory. The string/path I'm supplying to
. The directory I'm ultimately attempting to feed to
is ra_docs. Here is the directory structure (
means directory):


And just for the sake of being thorough, here is the function I'm running.

public static function directoryToArray($directory)
$result = array();

$currentDirectory = scandir($directory);
foreach ($currentDirectory as $key => $value)
if(!in_array($value, array(".","..")))
if (is_dir($directory . DIRECTORY_SEPARATOR . $value))
$result[$value] = dirToArray($directory . DIRECTORY_SEPARATOR . $value);
$result[] = $value;

return $result;

Any ideas?

Answer Source

If I change your code a little, changing public static function directoryToArray to function dirToArray, to match the call to dirToArray seen inside the function, the function works as I would expect.

The problem is either that inconsistency or what you are passing to it. I'll begin with the latter.

For a start, as mentioned in a comment by The Shift Exchange, you are passing in public/public as part of your string, and the directory structure you show in your question does not have such a path.

Second, you are passing an absolute path. PHP is trying to open the directory staffportal in the root directory /, since you started the string with a /. But presumably the staffportal directory is not directly in your filesystem root.

From your directory structure it would appear that staffportal is the root of your Laravel application. You can get the path to that via Laravel's built in base_path helper function (see the Laravel docs). Or, since the directory you're looking for is inside public, you can use the function which gives you the path directly to there, public_path (from the same docs).

Try passing in the path like this:

dirToArray(public_path() . '/documents/ra_docs')

(You could use DIRECTORY_SEPARATOR instead of the slashes there if you have portability concerns and wanted to match the style of your function.)

I imagine, though, that you did intend that function to be a static function on your model. So if you were in fact passing the path properly and so the above did not help, the error may be in your function where you attempt to recurse with a call to dirToArray -- this should be self::directoryToArray since you have declared this as a static function of a class.