如何在Laravel中创建目录和文件

时间:2019-03-05 04:15:01

标签: laravel laravel-5

我想在laravel https://laravel.com/docs/5.8/localization中实现本地化

我希望允许用户设置.json文件并上传键值转换。

要实现此目的,我需要在resources/lang/' . $request->language上创建一个目录,即$path = base_path('resources/lang/' . $request->language . '/');,然后创建一个json文件$request->language. '.json'

我尝试过

File::makeDirectory(base_path()."'resources/lang/' . $request->language . '/'", $mode = 0777, true, true);

然后

//Write File
$newJsonString = json_encode($request->translation, JSON_PRETTY_PRINT);
file_put_contents(base_path($path . $request->language. '.json'), stripslashes($newJsonString));

由于某些原因,它甚至不会创建目录。我会丢失什么吗?

1 个答案:

答案 0 :(得分:0)

我通过这样的测试创建了目录,请确认您在配置文件夹中是否为 filesystem.php ,并具有存储文件夹的权限。

// This will create folder in storage/app/folder_name
Route::get('/test',function(){
    Storage::disk('local')->makeDirectory('app/testFolder');
});

// This will create folder in resources/lang/folder_name
Route::get('/test',function(){
    $result = File::makeDirectory(base_path().'/resources/lang/testFolder');
    dd($result); // return true if folder created
});


// For more clarity try running this 
Route::get('/test',function(){
    $langs = ['en', 'fr', 'de','bs'];
    foreach ($langs as $key) {
        $path = base_path().'/resources/lang/'.$key;
        if (!File::exists($path)){
            $result = File::makeDirectory($path);
            dump("New Folder Created : ".$key);
        }else{
            dump("Folder Already Exist : ".$key);
        }
    }
    dd("ALL DONE");
});

我希望这对您有帮助