1. Go to this page and download the library: Download spatie/laravel-options library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
spatie / laravel-options example snippets
enum Hobbit: string
{
case Frodo = 'frodo';
case Sam = 'sam';
case Merry = 'merry';
case Pippin = 'pippin';
}
return [
/*
* The key used in an option to describe the label of the option
*/
'label_key' => 'label',
/*
* The key used in an option to describe the value of the option
*/
'value_key' => 'value',
];
Options::forEnum(Hobbit::class);
Options::forEnum(Hobbit::class)->toArray();
Options::forEnum(Hobbit::class)->toJson();
class ShowHobbitsController{
public function __invoke(RingBearer $ringBearer){
return [
'ring_bearer' => $ringBearer,
'hobbit_options' => Options::forEnum(Hobbit::class)
]
}
}
Options::forEnum(Hobbit::class)->nullable(label: 'Gandalf', value: 'You Shall Not Pass');
return [
/*
* The key used in an option to describe the label of the option
*/
'label_key' => 'name',
/*
* The key used in an option to describe the value of the option
*/
'value_key' => 'id',
];
Options::forModels(
Wizard::class,
label: fn(Wizard $wizard) => $wizard->getUuid(),
value: fn(Wizard $wizard) => $wizard->getName(),
); // A lot of times within your code base
class Wizard extends Model implements Selectable
{
public function toSelectOption(): SelectOption
{
return new SelectOption(
$this->getName(),
$this->getUuid()
)
}
}
Options::forModels(Wizard::class);
public function toSelectOption(): SelectOption
{
return new SelectOption(
$this->getName(),
$this->getUuid(),
['color' => $this->color]
)
}