skip to Main Content

this is my laravel code, however im having problems writing down in the locales files. If i only right the title it works, however if i also add the description only the description is written and the title ignored. I have tried multiple solutions in other forums, chatGPT, but still cant fix this problem.

Can someone please help me?

<?php

namespace AppLivewire;

use AppModelsService;
use AppModelsServiceCategory;
use CarbonCarbon;
use LivewireComponent;
use StichozaGoogleTranslateGoogleTranslate;
use IlluminateSupportFacadesLog;

class ManageServices extends Component
{
    public $name;
    public $description;
    public $price;
    public $duration;
    public $category;

    public function render()
    {
        $categories = ServiceCategory::get();
        $services = Service::with('category')->get();
        return view('livewire.manage-services', ['services' => $services, 'categories' => $categories]);
    }

    public function save()
    {
        try {
            $this->validate([
                'name' => 'required|string|min:1',
                'description' => 'required|string|min:1',
                'price' => 'required|numeric|min:1',
                'duration' => 'required|numeric|min:1',
                'category' => 'required|numeric',
            ]);

            $currentDate = Carbon::now()->format('Ymd');

            $randomString = $this->generateRandomString(10);

            $uniqueTitleKey = 'service_' . $currentDate . '_' . $randomString . '_title';
            $uniqueDescKey = 'service_' . $currentDate . '_' . $randomString . '_desc';

            $this->updateLocaleFiles($uniqueTitleKey, $this->name);
            $this->updateLocaleFiles($uniqueDescKey, $this->description);

            $service = new Service();
            $service->name = $uniqueTitleKey;
            $service->description = $uniqueDescKey;
            $service->price = $this->price;
            $service->duration = $this->duration;
            $service->category_id = $this->category;
            $service->save();

            session()->flash('flash.banner', trans('services.created'));
            session()->flash('flash.bannerStyle', 'success');
            return redirect()->route('manage_services');
        } catch (IlluminateValidationValidationException $e) {
            $errors = $e->validator->getMessageBag()->all();

            session()->flash('flash.banner', $errors[0]);
            session()->flash('flash.bannerStyle', 'danger');
            return redirect()->route('manage_services');
        } catch (Exception $e) {
            Log::error('Error saving service: ' . $e->getMessage());
            session()->flash('flash.banner', trans('services.error_creating'));
            session()->flash('flash.bannerStyle', 'danger');
            return redirect()->route('manage_services');
        }
    }

    private function generateRandomString($length = 10)
    {
        return substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length);
    }

    private function updateLocaleFiles($key, $value)
    {
        $currentLocale = app()->getLocale();
        $targetLocales = ['pt', 'es', 'fr', 'it', 'nl', 'en'];

        // Remove the current locale from the target locales array if it exists
        $index = array_search($currentLocale, $targetLocales);
        if ($index !== false) {
            unset($targetLocales[$index]);
        }

        // Update the locale file for the current locale first
        $this->updateLocaleFile($key, $value, $currentLocale);

        // Iterate through the remaining target locales
        foreach ($targetLocales as $locale) {
            try {
                $translatedValue = $this->translate($value, $currentLocale, $locale);
                $this->updateLocaleFile($key, $translatedValue, $locale);
            } catch (Exception $e) {
                Log::error("Error translating to locale '{$locale}': " . $e->getMessage());
            }
        }
    }


    private function updateLocaleFile($key, $value, $locale)
    {
        try {
            $localePath = base_path("lang/{$locale}");


            if (!is_dir($localePath)) {
                mkdir($localePath, 0755, true);
            }

            $localeFile = "{$localePath}/services.php";

            if (file_exists($localeFile)) {
                $localeArray = include($localeFile);
            } else {
                $localeArray = [];
            }

            $localeArray[$key] = $value;

            file_put_contents($localeFile, "<?phpnnreturn " . var_export($localeArray, true) . ";n");

            Log::info("Locale file for '{$locale}' updated successfully.");
        } catch (Exception $e) {
            Log::error("Error updating locale file for '{$locale}': " . $e->getMessage());
        }
    }

    private function translate($text, $sourceLocale, $targetLocale)
    {
        $tr = new GoogleTranslate();
        $tr->setSource($sourceLocale);
        $tr->setTarget($targetLocale);
        return $tr->translate($text);
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    I ended up using File:: but thank you very much for the knowledge abou the file_put_contents

    <?php
    
    namespace AppLivewire;
    
    use AppModelsService;
    use AppModelsServiceCategory;
    use CarbonCarbon;
    use IlluminateSupportFacadesFile;
    use LivewireComponent;
    use StichozaGoogleTranslateGoogleTranslate;
    use IlluminateSupportFacadesLog;
    use IlluminateSupportFacadesStorage;
    
    class ManageServices extends Component
    {
        public $name;
        public $description;
        public $price;
        public $duration;
        public $category;
    
        public function render()
        {
            $categories = ServiceCategory::get();
            $services = Service::with('category')->get();
            return view('livewire.manage-services', ['services' => $services, 'categories' => $categories]);
        }
    
        public function save()
        {
            try {
                $this->validate([
                    'name' => 'required|string|min:1',
                    'description' => 'required|string|min:1',
                    'price' => 'required|numeric|min:1',
                    'duration' => 'required|numeric|min:1',
                    'category' => 'required|numeric',
                ]);
    
                $currentDate = Carbon::now()->format('Ymd');
    
                $randomString = $this->generateRandomString(10);
    
                $uniqueTitleKey = 'service_' . $currentDate . '_' . $randomString . '_title';
                $uniqueDescKey = 'service_' . $currentDate . '_' . $randomString . '_desc';
    
                $this->updateLocaleFiles($uniqueTitleKey, $this->name);
                $this->updateLocaleFiles($uniqueDescKey, $this->description);
    
                $service = new Service();
                $service->name = $uniqueTitleKey;
                $service->description = $uniqueDescKey;
                $service->price = $this->price;
                $service->duration = $this->duration;
                $service->category_id = $this->category;
                $service->save();
    
                session()->flash('flash.banner', trans('services.created'));
                session()->flash('flash.bannerStyle', 'success');
                return redirect()->route('manage_services');
            } catch (IlluminateValidationValidationException $e) {
                $errors = $e->validator->getMessageBag()->all();
    
                session()->flash('flash.banner', $errors[0]);
                session()->flash('flash.bannerStyle', 'danger');
                return redirect()->route('manage_services');
            } catch (Exception $e) {
                Log::error('Error saving service: ' . $e->getMessage());
    
                dd($e->getMessage());
    
                session()->flash('flash.banner', trans('services.error_creating'));
                session()->flash('flash.bannerStyle', 'danger');
                return redirect()->route('manage_services');
            }
        }
    
        private function generateRandomString($length = 10)
        {
            return substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length);
        }
    
        private function updateLocaleFiles($key, $value)
        {
            $currentLocale = app()->getLocale();
            $targetLocales = ['pt', 'es', 'fr', 'it', 'nl', 'en'];
    
            // Remove the current locale from the target locales array if it exists
            $index = array_search($currentLocale, $targetLocales);
            if ($index !== false) {
                unset($targetLocales[$index]);
            }
    
            // Update the locale file for the current locale first
            $this->updateLocaleFile($key, $value, $currentLocale);
    
            // Iterate through the remaining target locales
            foreach ($targetLocales as $locale) {
                try {
                    $translatedValue = $this->translate($value, $currentLocale, $locale);
                    $this->updateLocaleFile($key, $translatedValue, $locale);
                } catch (Exception $e) {
                    Log::error("Error translating to locale '{$locale}': " . $e->getMessage());
                }
            }
        }
    
        private function updateLocaleFile($key, $value, $locale)
        {
            $filePath = base_path("resources/lang/{$locale}/services.php");
    
            $translations = [];
    
            if (File::exists($filePath)) {
                $translations = require $filePath;
            }
    
            $translations[$key] = $value;
    
            $content = "<?phpnnreturn " . var_export($translations, true) . ";n";
    
            $directory = dirname($filePath);
            if (!File::isDirectory($directory)) {
                File::makeDirectory($directory, 0755, true);
            }
    
            try {
                File::put($filePath, $content);
            } catch (Exception $e) {
                Log::error("Failed to write to file '{$filePath}': " . $e->getMessage());
            }
        }
    
        private function translate($text, $sourceLocale, $targetLocale)
        {
            $tr = new GoogleTranslate();
            $tr->setSource($sourceLocale);
            $tr->setTarget($targetLocale);
            return $tr->translate($text);
        }
    }
    
    

  2. You are using file_put_contents to write your output. The PHP docs for file_put_contents say:

    This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.

    So what you’re doing is overwriting any contents already in the file every time you write. You could start your process with fopen() and do your output with fwrite() then end your process with fclose() but Laravel offers some better options in the Storage facade.

    Storage::append('file.log', 'Appended Text');
    

    The Storage::append() method allows you to write to the end of the given file without overwriting the existing contents

    https://laravel.com/docs/11.x/filesystem#prepending-appending-to-files

    Alternatively use the FILE_APPEND flag on file_put_contents:

    file_put_contents($localeFile, "<?phpnnreturn " . var_export($localeArray, true) . ";n", FILE_APPEND);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search