samedi 5 août 2017

Laravel resource_path() to get list of files doesn't work, but absolute path does?

I need to be able to pass translations to my Vue SPA based on the current locale, and refresh the language if the locale changes. I wrote a method in my controller to look up the file names in the current locale and pull the various messages out of each of them. However, my File::files() call only works if I hard code the path to my lang directory; if I concatenate everything together using resource_path(), it pulls the files in my drive's root location. Why would hardcoding the path work when piecing it together at runtime does not?

This works:

private function getLangJson($locale = null)
{
    $fileDir = "D:\\web\\projects\\MyProject\\resources\\lang\\en";
    $langFiles = File::files($fileDir);
    $trans = [];
    foreach ($langFiles as $f)
    {
        $filename = basename($f, '.php');
        $langFilesArray = Lang::get($filename);
        if (count($langFilesArray) > 0)
        {
            $trans[$filename] = [];
            foreach ($langFilesArray as $key => $value)
                $trans[$filename][$key] = $value;
        }
    }
    return json_encode($trans);
}

This does not work:

private function getLangJson($locale = null)
{
    $fileDir = resource_path() . '\\lang\\' . $locale !== null ? $locale : app()->getLocale();
    $langFiles = File::files($fileDir);
    $trans = [];
    foreach ($langFiles as $f)
    {
        $filename = basename($f, '.php');
        $langFilesArray = Lang::get($filename);
        if (count($langFilesArray) > 0)
        {
            $trans[$filename] = [];
            foreach ($langFilesArray as $key => $value)
                $trans[$filename][$key] = $value;
        }
    }
    return json_encode($trans);
}

When I inspect both ways of doing it, I get the same exact result:

D:\web\projects\UpTheAnte\resources\lang\en
string(43) "D:\web\projects\UpTheAnte\resources\lang\en" 
D:\web\projects\UpTheAnte\resources\lang\en
string(43) "D:\web\projects\UpTheAnte\resources\lang\en"



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2ue22Vo
via IFTTT

Aucun commentaire:

Enregistrer un commentaire