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

0.1 2022-07-04 10:47 UTC

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

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.