DEV Community

Cover image for Storing Variables in a Laravel App Database
Timothy Soladoye
Timothy Soladoye

Posted on

Storing Variables in a Laravel App Database

How I use settings table to manage variables across Laravel app database

While working on Laravel applications that requires a lot of configurations, I had a problem with storing the data in the database

Do I keep creating new tables anytime I want to store a setting?

Do I keep adding new columns on existing tables to store these variables?

I then came up with the settings table approach

It's a simple but effective approach.

I use a table settings to store all details of a variable

I can query the table to get current value of the variable

I can update the table to store updated value

php artisan make:model Setting -m
//This will create a Setting Model and settings_table migration
Enter fullscreen mode Exit fullscreen mode
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Setting extends Model
{
    protected $fillable=['name','slug','value','description'];

    protected $casts=[
        'value'=>'array'
    ];
}
Enter fullscreen mode Exit fullscreen mode

The settings table has the following columns

  • name : to store the name of the setting item
  • slug : to store a unique name of the setting item for querying
  • value : to store the value of the setting item
  • description : to store details of the setting item

the value column is casted to array; this is to handle setting values that are in an array form

Querying the table

The settings table is queried either using eloquent or DB facade

//array values
$approved_users=\App\Setting::where('slug','approved_users')->first()->value ?? [];

//integer value
$percentage=\App\Setting::where('slug','percentage')->first()->value ?? 20;

//boolean value
$use_old_process=\DB::table('settings')->where('slug','use_old_process')->value('value') ?? 1;
Enter fullscreen mode Exit fullscreen mode

Conclusion

This is how I handle some settings in Laravel applications with a lot of configurations. It is not a standard to be enforced. It solved my problem, it could solve yours

If you have a better way of storing variables in an application, please leave a comment.

Cheers 😊

Top comments (0)