PHP code example of geekk-net / laravel-enum
1. Go to this page and download the library: Download geekk-net/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/ */
geekk-net / laravel-enum example snippets
namespace App\Enums;
use MadWeb\Enum\Enum;
/**
* @method static PostStatusEnum FOO()
* @method static PostStatusEnum BAR()
* @method static PostStatusEnum BAZ()
*/
final class PostStatusEnum extends Enum
{
const __default = self::PENDING;
const PUBLISHED = 'published';
const PENDING = 'pending';
const DRAFT = 'draft';
}
class Post extends Model
{
protected $fillable = ['title', 'status'];
protected $casts = [
'status' => PostStatusEnum::class,
];
}
$post = Post::first();
$status = $post->status; // PostStatusEnum
$post->status = PostStatusEnum::PENDING();
$post->save();
// resources/lang/en/enums.php
return [
PostStatusEnum::class => [
PostStatusEnum::PENDING => 'Pending Label',
PostStatusEnum::PUBLISHED => 'Published Label',
PostStatusEnum::DRAFT => 'Draft Label',
],
];
PostStatusEnum::PENDING()->label(); // Pending Label
// config/enum.php
return [
'lang_file_path' => 'custom.path.to.enums',
];
// resources/lang/en/validation.php
return [
//...
'enum' => 'Custom validation message form enum attribute :attribute',
];
PostStatusEnum::getRandomKey(); // Returns 'PUBLISHED` or `PENDING` or `DRAFT`
PostStatusEnum::getRandomValue(); // Returns 'published` or `pending` or `draft`
PostStatusEnum::PUBLISHED()->label(); // Returns 'published` or custom label declared in a lang file
PostStatusEnum::labels(); // Returns ['published`, 'pending', 'draft'] or array of custom labels declared in a lang file
$status = PostStatusEnum::PENDING();
PostStatusEnum::PUBLISHED()->is($status); // false
PostStatusEnum::PENDING()->is($status); // true
// or
PostStatusEnum::PUBLISHED()->is($status->getValue()); // false
PostStatusEnum::PENDING()->is($status->getValue()); // true
// or check one of multiple values
$status->is([PostStatusEnum::DRAFT(), PostStatusEnum::PUBLISHED()]) // false
$status->is([PostStatusEnum::DRAFT(), PostStatusEnum::PENDING()]) // true
PostStatusEnum::rule(); // new EnumRule(PostStatusEnum::class);
bash
php artisan make:enum PostStatusEnum
bash
php artisan make:enum PostStatusEnum DRAFT=draft PENDING=pending PUBLISHED=published
bash
php artisan vendor:publish --provider=MadWeb\\Enum\\EnumServiceProvider
php
public function store(Request $request)
{
$this->validate($request, [
'status' => ['::rule()],
]);
}
php
public function store(Request $request)
{
$this->validate($request, [
'status' => ['::ruleByKey()],
]);
}