qcod / laravel-app-settings

Store settings in database with a manager UI for your Laravel app
MIT License
338 stars 53 forks source link

Default value for removed image is different from an image that was never set #31

Open Bibendus83 opened 4 years ago

Bibendus83 commented 4 years ago

I noticed that calling setting('img_setting', 'default_img') on a setting of type image has a different behavior depending if the value has never been set or if the value has been set and then the image has been removed later. In the first case default_img is returned, in the second one null is returned. I think that in both cases default_img should be returned.

hellodit commented 3 years ago

It's fixed now? I try to call image settings, but it has not called the value

Bibendus83 commented 3 years ago

It's fixed now? I try to call image settings, but it has not called the value

I don't see any fix on the repository, I still have the problem.

Bibendus83 commented 3 months ago

The solution is to change in the AppSettings->uploadFile() method $this->set($settingName, null); into $this->remove($settingName);

As the repository seems dead and QCod\AppSettings\Setting\AppSettings is hardcoded in multiple places to make it easily instantiable, a quick solution is to redefine the store function using a custom AppSettingController so you can force a remove of the unused keys.

Example:

App\Http\Controllers\AppSettingController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use QCod\AppSettings\Setting\AppSettings;
use Illuminate\Support\Facades\DB;
use QCod\AppSettings\Controllers\AppSettingController as DefaultAppSettingController;

class AppSettingController extends DefaultAppSettingController
{
    public function store(Request $request, AppSettings $appSettings)
    {
        DB::beginTransaction();

        $return = parent::store($request, $appSettings);

        // Cycles all the settings defined in the config file to force remove files and images
        // Fixes https://github.com/qcod/laravel-app-settings/issues/31
        $allDefinedSettings = $appSettings->getAllSettingFields();
        $allDefinedSettings->each(function ($setting) use ($request, $appSettings) {
            $settingName = $setting['name'];
            $type = $setting['type'];

            if (in_array($type, ['file', 'image']) && !isset($setting['mutator'])) {
                if ($request->has('remove_file_' . $settingName)) {
                    $appSettings->remove($settingName);
                }
            }
        });

        DB::commit();
        return $return;
    }
}

config/app_settings.php

change

'controller' => '\QCod\AppSettings\Controllers\AppSettingController',

to

controller' => 'App\Http\Controllers\AppSettingController',