Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create a directory and file in Laravel

I would like to achieve localization in laravel https://laravel.com/docs/5.8/localization

I would want to allow a user to set up a .json file and upload the key value translations.

To achieve this, I need to create a directory on resources/lang/' . $request->language that is $path = base_path('resources/lang/' . $request->language . '/'); then a json file $request->language. '.json'

I tried this

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

Then

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

For some reasons, it does not create even the directory. Could I be missing something?

like image 634
User101 Avatar asked Sep 05 '25 03:09

User101


1 Answers

I created directory by testing like this, please verify you're filesystem.php in config folder and the permission of the storage folder.

// 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");
});

I hope this helps

like image 68
Vipertecpro Avatar answered Sep 08 '25 00:09

Vipertecpro