lundi 30 août 2021

show default object from model if table is empty

I have 2 models named setting and settings one controller settingController

following is database table name setting

id key    Value      created_at       updated_at

if this table is empty then I want to show some default values. following my model codes

namespace App;

use Illuminate\Database\Eloquent\Model;

class Setting extends Model
{
    protected $fillable = ['key', 'value'];
}

and settings model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Settings extends Model
{
    const options = [
        'key' => 'some_val',
        'value' => 0
    ];

public function __construct()
{

    foreach (self::options as $option => $default_value) {
        $this->{$option} = $default_value;
    }
    
    $settings = Setting::all();
    foreach ($settings as $setting) {
        $this->{$setting->key} = $setting->value;
    }
}

}

Now while model call in controller

public function getEdit()
{
    $settings = Settings::all();
    dd($settings);
    return view::make('admin/settings', compact('settings'));
}

If there is data in the table then it should show the table data. if no data then it should show the default options.

Now I am only getting empty while there is no data in a table. How can i solve above issue?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire