1. Go to this page and download the library: Download spatie/laravel-enum 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-enum example snippets
// a Laravel specific base class
use Spatie\Enum\Laravel\Enum;
/**
* @method static self DRAFT()
* @method static self PREVIEW()
* @method static self PUBLISHED()
* @method static self ARCHIVED()
*/
final class StatusEnum extends Enum {}
use Illuminate\Database\Eloquent\Model;
class TestModel extends Model
{
protected $casts = [
'status' => StatusEnum::class,
'nullable_enum' => StatusEnum::class.':nullable',
'array_of_enums' => StatusEnum::class.':collection',
'nullable_array_of_enums' => StatusEnum::class.':collection,nullable',
];
}
$model = new TestModel();
$model->status = StatusEnum::DRAFT();
$model->status->equals(StatusEnum::DRAFT());
use Spatie\Enum\Laravel\Rules\EnumRule;
$rules = [
'status' => new EnumRule(StatusEnum::class),
];
use Spatie\Enum\Laravel\Http\EnumRequest;
$enums = [
// cast the status key independent of it's data set
'status' => StatusEnum::class,
// cast the status only in the request query params
EnumRequest::REQUEST_QUERY => [
'status' => StatusEnum::class,
],
// cast the status only in the request post data
EnumRequest::REQUEST_REQUEST => [
'status' => StatusEnum::class,
],
// cast the status only in the request route params
EnumRequest::REQUEST_ROUTE => [
'status' => StatusEnum::class,
],
];
use Illuminate\Foundation\Http\FormRequest;
use Spatie\Enum\Laravel\Http\Requests\TransformsEnums;
use Spatie\Enum\Laravel\Rules\EnumRule;
class StatusFormRequest extends FormRequest
{
use TransformsEnums;
public function rules(): array
{
return [
'status' => new EnumRule(StatusEnum::class),
'properties.level' => new EnumRule(LevelEnum::class),
];
}
public function enums(): array
{
return [
'status' => StatusEnum::class,
'properties.level' => LevelEnum::class,
];
}
}
protected function passedValidation()
{
$this->transformEnums($this->enums());
// ...
}
Route::get('/posts/{status}', function (StatusEnum $status) {
return $status;
});
Route::enum('status', StatusEnum::class);
Route::get('/posts/{status}', function (Request $request) {
return $request->route('status');
});
class ShowCustomer extends Component
{
public StatusEnum $statusEnum;
public function mount($id)
{
$customer = Customer::find($id);
$this->statusEnum = $customer->status;
}
public function render()
{
return view('livewire.customer');
}
}
use Livewire\Wireable;
/**
* @method static self pending()
* @method static self active()
*/
final class StatusEnum implements Wireable
{}