A simple package that allows you to cache all rows on a relationship model for use in select arrays on forms.
You can install the package via composer:
composer require chrisabey84/laravel-cached-options-list
You can publish the config file with:
php artisan vendor:publish --provider="Chrisabey84\LaravelCachedOptionsList\LaravelCachedOptionsListServiceProvider
This is the contents of the published config file:
return [
'key' => 'id', //The index/key column for the select options array
'value' => 'name', //The value column for the select options array
];
Adding the HasCachedOptionsList
trait to any of your models will provide the following functionality:
$rows = \App\Models\MyModel::asSelectArray();
Will retrieve all rows as an associative array which can then be used in your blade templates to populate the option in a select box:
<select name="mySelectBox">
@foreach($rows as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
@endforeach
</select>
By default asSelectArray()
will retrieve all rows from the database table however, you can customise this behavior by overriding the following method in your model which must return a Builder
instance:
protected static function buildQuery(): Builder
{
return static::query();
}
The cache will be automatically cleared when creating, updating or deleting your models.
To manually clear the cache, you can either call:
\App\Models\MyModel::clearOptionsCache();
Or use the handy artisan command with the model name as the argument:
php artisan cached-options:clear '\App\Models\MyModel'
composer test
The MIT License (MIT). Please see License File for more information.