Laravel GLOB public path

8k views Asked by At

In Laravel I want to get all images from a dir, I just have a problem getting the path to the public folder.

    $images = [];

    foreach(File::glob('/public/img/uploads/*.*') as $filename) {
        $images[] = $filename;
    }

If I use this function it returns nothing, I also tried using public_path() but that returns the full path including my F:// dir.

2

There are 2 answers

0
Marcin Orlowski On

I just have a problem getting the path to the public folder. I also tried using public_path() but that returns the full path including my F:// dir.

It does it as manual reads:

base_path()
Get the fully qualified path to the root of the application install.

config_path()
Get the fully qualified path to the config directory.

public_path()
Get the fully qualified path to the public directory.

storage_path()
Get the fully qualified path to the storage directory.

'/public/img/uploads/*.*'

I doubt your public directory is in your root folder and this is what your absolute path you used points to, so use what public_path() returns - it rather is nothing to bother it is full qualified path.

0
Brian Hellekin On

Laravel glob function returns an array with the absolute path of the files it found. It's important to remember that you need to pass the absolute path in the argument too.

In your case, since you want to find files inside the public folder, you can use the public_path() helper as suggested by @Marcin Orlowski to get the desired absolute path; other helpers can be used in case you want to search in different locations.

So, the proper way to call glob in your code is the line below:

$images = File::glob(public_path() . '/img/uploads/*.*');

However, probably you don't want the absolute path, just the path relative to the public folder. In this case, you can use the basename function to get rid of the absolute path and add the path parts you want:

$images = [];
foreach (File::glob(public_path() . '/img/uploads/*.*') as $filename) {
    $images[] = '/img/uploads/' . basename($filename);
}

With array map instead of a foreach:

$images = array_map(function($filename) {
    return '/img/uploads/' . basename($filename);
}, File::glob(public_path() . '/img/uploads/*.*'));

Note: Laravel Glob is a wrapper for the PHP glob() function.