DEV Community

TRUNG VU
TRUNG VU

Posted on

 

Set global variable from Settings table in Laravel

The idea is that I’m fetching table values (also caching it) and made a SettingServiceProvider to be able to access it as a configuration variable later on.

First, we need to create Setting model and migration by following artisan

php artisan make:model Models\Setting -m
Enter fullscreen mode Exit fullscreen mode

Configure for Setting migration file

// database\migration\xxxx_xx_xx_xxxxxx_create_settings_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateSettingsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('settings', function (Blueprint $table) {
            $table->smallIncrements('id');
            $table->string('name')->unique();
            $table->text('value');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('settings');
    }
}
Enter fullscreen mode Exit fullscreen mode

Configure for Setting model file

// app\Models\Setting.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Setting extends Model
{
    protected $guarded = [];
}
Enter fullscreen mode Exit fullscreen mode

Run following artisan

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

And create a service provider

php artisan make:provider SettingServiceProvider
Enter fullscreen mode Exit fullscreen mode

We will use cache and set expire time for Setting by bellow code

// app\Provider\SettingServiceProvider.php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Cache\Factory;
use App\Models\Setting;

class SettingServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot(Factory $cache, Setting $settings)
    {
        $settings = $cache->remember('settings', 60, function() use ($settings){
            // Laravel >= 5.2, use 'lists' instead of 'pluck' for Laravel <= 5.1
            return $settings->pluck('value', 'name')->all();
        });
        config()->set('settings', $settings);
    }
}
Enter fullscreen mode Exit fullscreen mode

Register it into providers section of config/app.php file

// config\app.php

'providers' => [
    // ...
    App\Providers\SettingServiceProvider::class,
],
Enter fullscreen mode Exit fullscreen mode

Create a controller class for Setting

php artisan make:controller Backend\SettingController
Enter fullscreen mode Exit fullscreen mode

Add following logic code

// app\Http\Controllers\Backend\SettingController.php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Contracts\Cache\Factory;
use App\Models\Setting;

class SettingController extends Controller
{
    public function index()
    {
        $settings = Setting::all();
        return view('backend.modules.setting.index', compact('settings'))->withTitle('List of Settings');
    }

    public function edit(Setting $setting)
    {
        return view('backend.modules.setting.edit', compact('setting'))->withTitle('Edit a Setting');
    }

    public function update(Request $request, Factory $cache, Setting $setting)
    {
        if ($request->isMethod('put')) {
            $rules = [
                'value' => 'required'
            ];
            $messages = [
                'value.required' => 'Value of Setting is required.'
            ];
            $this->validate($request, $rules, $messages);
            $setting->value = $request->value;
            $setting->save();
            // When the settings have been updated, clear the cache for the key 'settings'
            $cache->forget('settings');
            return redirect()->route('admin.settings.index')->with('success', 'Item has been updated successfully.');
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In anywhere, we just only access via the config() helper

config('settings.variable_name')
Enter fullscreen mode Exit fullscreen mode

Reference: https://stackoverflow.com/a/34126882/3868376

Thanks tommy https://stackoverflow.com/users/3726647/tommy

Happy Coding :)

Oldest comments (0)

16 Libraries You Should Know as a React Developer

Being a modern React developer is not about knowing just React itself. To stay competitive, it is highly recommended to explore the whole ecosystem. This article contains some of the most useful React component libraries to speed up your developer workflow.