Build your first Laravel package · Part 2 of 4
The settings feature
The migration, the model, the Settings class with its one cached read, and the facade. By the end the package does something, and a route in your app proves it with the types intact.
By Abhishek Fouzdar · Updated
Part 1 left you with a package Laravel can find and nothing inside it. This part adds the feature: a table, a model, a class that reads the table once and caches it, and a facade so the class reads like Laravel. Every file here is one you have written in an app before. What changes is where it lives and how the package tells Laravel about it.
One more dependency
The package is about to use Eloquent, so it should say so. If you followed part 1 literally, add illuminate/contracts and illuminate/database next to illuminate/support in the package's composer.json; the example repository has had them since its first commit:
"require": {
"php": "^8.2",
"illuminate/contracts": "^12.0|^13.0",
"illuminate/database": "^12.0|^13.0",
"illuminate/support": "^12.0|^13.0"
}
illuminate/contracts is there for the cache interface we type-hint below. Your app already has all of these through laravel/framework, so nothing new downloads, but a package that uses Eloquent without declaring it will break in an app that installs it differently. In the app, run composer update shipbytes/laravel-settings so Composer re-reads the package's manifest. Code changes do not need this, because of the symlink; manifest changes do.
The migration
Create database/migrations/2026_01_01_000000_create_settings_table.php:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create(config('settings.table', 'settings'), function (Blueprint $table) {
$table->id();
$table->string('key')->unique();
$table->json('value')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists(config('settings.table', 'settings'));
}
};
Two decisions are packed into this small file.
The table name comes from the config, with 'settings' as the fallback. In part 1 we promised users they could rename the table; this is where that promise is kept.
The value column is JSON, not a string. A settings table that stores everything as text makes "false" come back as a string that is truthy in PHP, which is the kind of bug that costs an afternoon. JSON keeps a boolean a boolean, an integer an integer and an array an array. The column is nullable so a setting can hold null on purpose.
The date in the filename is fixed rather than today's date. A package's migrations should sort predictably among the app's own, and a date far enough back guarantees it runs before anything the app adds later.
The model
Create src/Models/Setting.php:
<?php
namespace Shipbytes\Settings\Models;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
protected $fillable = ['key', 'value'];
protected $casts = [
'value' => 'json',
];
public function getTable(): string
{
return config('settings.table', 'settings');
}
}
The json cast is the other half of the column decision: Eloquent encodes on the way in and decodes on the way out, so the rest of the package never sees JSON at all. Overriding getTable() instead of setting $table lets the name come from config at runtime, which a property cannot do.
The Settings class
This is the one piece of real logic in the package. Create src/Settings.php:
<?php
namespace Shipbytes\Settings;
use Illuminate\Contracts\Cache\Repository as Cache;
use Shipbytes\Settings\Models\Setting;
class Settings
{
/** @var array<string, mixed>|null */
protected ?array $loaded = null;
public function __construct(
protected Cache $cache,
protected string $cacheKey,
) {}
public function get(string $key, mixed $default = null): mixed
{
$all = $this->all();
return array_key_exists($key, $all) ? $all[$key] : $default;
}
public function has(string $key): bool
{
return array_key_exists($key, $this->all());
}
public function set(string $key, mixed $value): void
{
Setting::query()->updateOrCreate(['key' => $key], ['value' => $value]);
$this->flush();
}
public function forget(string $key): void
{
Setting::query()->where('key', $key)->delete();
$this->flush();
}
/** @return array<string, mixed> */
public function all(): array
{
return $this->loaded ??= $this->cache->rememberForever(
$this->cacheKey,
fn () => Setting::query()->pluck('value', 'key')->all(),
);
}
public function flush(): void
{
$this->loaded = null;
$this->cache->forget($this->cacheKey);
}
}
Read all() first, because everything else goes through it. A settings table is small and read on almost every request, so the package reads the whole table as one query and keeps the result in the cache under one key, forever. rememberForever returns the cached array if there is one and otherwise runs the closure, stores the result and returns it.
The ??= on $loaded adds a second, shorter-lived layer: once this object has the array, later calls in the same request do not even touch the cache. In the service provider we will make the object a singleton, so "this object" means "this request".
get uses array_key_exists rather than isset or ??. A setting deliberately set to null exists, and should come back as null, not as the default. isset would say it does not exist.
set and forget both end with flush(), which clears both layers. The next read anywhere, in this request or the next, goes back to the database. That is the whole invalidation strategy, and it is enough: writes are rare, reads are constant, and one query after a write is a fine price.
The constructor takes the cache contract, not the Cache facade. The class then works with any store and can be handed a fake in tests. Prefer this in package code; facades are convenient in apps and awkward to swap out.
The facade
Create src/Facades/Settings.php:
<?php
namespace Shipbytes\Settings\Facades;
use Illuminate\Support\Facades\Facade;
/**
* @method static mixed get(string $key, mixed $default = null)
* @method static bool has(string $key)
* @method static void set(string $key, mixed $value)
* @method static void forget(string $key)
* @method static array<string, mixed> all()
* @method static void flush()
*
* @see \Shipbytes\Settings\Settings
*/
class Settings extends Facade
{
protected static function getFacadeAccessor(): string
{
return \Shipbytes\Settings\Settings::class;
}
}
A facade is a static front door to an object in the container. getFacadeAccessor returns what to resolve, here the class name itself; Laravel resolves it and forwards the static call. The @method lines are not decoration: they are how your editor knows that Settings::get() exists and what it returns, because the facade class itself has no such method.
The facade and the class share a short name, which is why the facade sits in its own namespace. In the app, users import Shipbytes\Settings\Facades\Settings, and we add an alias in composer.json so that plain Settings works too:
"extra": {
"laravel": {
"providers": [
"Shipbytes\\Settings\\SettingsServiceProvider"
],
"aliases": {
"Settings": "Shipbytes\\Settings\\Facades\\Settings"
}
}
}
Wiring it up in the provider
Update src/SettingsServiceProvider.php:
<?php
namespace Shipbytes\Settings;
use Illuminate\Support\ServiceProvider;
class SettingsServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->mergeConfigFrom(__DIR__.'/../config/settings.php', 'settings');
$this->app->singleton(Settings::class, function ($app) {
return new Settings(
$app['cache']->store(config('settings.cache.store')),
config('settings.cache.key'),
);
});
}
public function boot(): void
{
$this->loadMigrationsFrom(__DIR__.'/../database/migrations');
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__.'/../config/settings.php' => config_path('settings.php'),
], 'settings-config');
}
}
}
Two additions. In register, the Settings object is bound as a singleton: built once per request, on first use, with the cache store and key from config. Nothing in this closure runs until someone actually resolves the class, so registering the package costs nothing on requests that never read a setting.
In boot, loadMigrationsFrom tells Laravel to include the package's migrations folder when php artisan migrate runs. Users do not copy the migration into their app; it runs from inside vendor/. That is the right default for a table the package owns.
Using it from the app
Run the migration in your app:
php artisan migrate
2026_01_01_000000_create_settings_table ......... DONE
Add a route to routes/web.php to see the facade work end to end:
use Shipbytes\Settings\Facades\Settings;
Route::get('/settings-demo', function () {
Settings::set('site_name', 'Acme');
return [
'site_name' => Settings::get('site_name'),
'registration_open' => Settings::get('registration_open', true),
];
});
Start the app with php artisan serve and open /settings-demo:
{"site_name":"Acme","registration_open":true}
Now set registration_open to false from Tinker and reload:
php artisan tinker --execute="Settings::set('registration_open', false);"
{"site_name":"Acme","registration_open":false}
That false is a real boolean, not the string "false". The JSON column and the cast did their job. Remove the demo route when you are done; it writes on every request, which is fine for a check and wrong for anything else.
Checkpoint
You should have:
database/migrations/…create_settings_table.php,src/Models/Setting.php,src/Settings.php,src/Facades/Settings.php, and the updated provider andcomposer.json;- a
settingstable in your app afterphp artisan migrate; - the demo route returning values with their types intact.
The matching commit is Part 2: the settings feature.
It works, and you proved it by hand. Part 3 makes the proof repeatable: tests that run without an app around the package.
New posts by email
Get new posts by email. Nothing else, no digests, unsubscribe in one click.
Comments
Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.
In this series
2 / 4