chrisabey84 / laravel-cached-options-list
A simple package that allows you to cache all rows on a relationship model for use in select arrays on forms
Requires
- php: ^8.0
- illuminate/contracts: ^9.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.8
- nunomaduro/collision: ^6.0
- nunomaduro/larastan: ^2.0.1
- orchestra/testbench: ^7.0
- pestphp/pest: ^1.21
- pestphp/pest-plugin-laravel: ^1.1
- phpstan/extension-installer: ^1.1
- phpstan/phpstan-deprecation-rules: ^1.0
- phpstan/phpstan-phpunit: ^1.0
- phpunit/phpunit: ^9.5
- spatie/laravel-ray: ^1.26
This package is auto-updated.
Last update: 2024-11-09 09:13:16 UTC
README
A simple package that allows you to cache all rows on a relationship model for use in select arrays on forms.
Installation
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 ];
Usage
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>
Custom Behavior
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(); }
Clearing The Cache
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'
Testing
composer test
Credits
License
The MIT License (MIT). Please see License File for more information.