PHP code example of mindtwo / native-enum

1. Go to this page and download the library: Download mindtwo/native-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/ */

    

mindtwo / native-enum example snippets


// Default:
php artisan make:enum UserRole

// Localized:
php artisan make:enum UserRole --localized

namespace App\Enums;

enum UserRole: int
{
    use BaseEnum;
    
    case ADMIN = 10;
    case CUSTOMER = 50;
}

UserRole::getRandomValue();
UserRole::getRandomName();
UserRole::getRandomInstance();
UserRole::asSelectArray();
UserRole::asArray();
UserRole::getValues();
UserRole::getNames();
UserRole::hasValue(50);
UserRole::hasName('ADMIN');

UserRole::getValues('ADMIN');
UserRole::getValues(UserRole::ADMIN);
UserRole::getValues([UserRole::ADMIN]);
UserRole::getValues('CUSTOMER');
UserRole::getValues(UserRole::CUSTOMER);
UserRole::getValues([UserRole::CUSTOMER]);

UserRole::getNames(10);
UserRole::getNames(50);
UserRole::getNames([10,50]);

UserRole::ADMIN(); // 10
UserRole::CUSTOMER(); // 50

use mindtwo\NativeEnum\Rules\EnumValue;

public function store(Request $request)
{
    $this->validate($request, [
        'user_role' => ['

new EnumValue(UserRole::class, false) // Turn off strict type checking.

use mindtwo\NativeEnum\Rules\EnumKey;

public function store(Request $request)
{
    $this->validate($request, [
        'user_role' => ['

use mindtwo\NativeEnum\Rules\Enum;

public function store(Request $request)
{
    $this->validate($request, [
        'user_role' => ['

namespace App\Enums;

enum UserRole: int implements LocalizedEnum
{
    use BaseEnum;
    
    case ADMIN = 10;
    case CUSTOMER = 50;
}

use \App\Enums;

return [

    Enums\UserRole::class => [
        Enums\UserRole::ADMIN->name => 'Administrator',
        Enums\UserRole::CUSTOMER->name => 'Customer',
    ],

];

Enums\UserRole::ADMIN->name(); // Returns "Administrator"

namespace App\Models;

use App\Enums\UserRole;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $casts = [
        'role' => UserRole::class,
    ];
}

protected $casts = [
    'role' => UserRole::class . ':nullable',
];

namespace App\Enums;

use Illuminate\Contracts\Database\Eloquent\Castable;

enum UserRole: int implements Castable
{
    use BaseEnum;
    
    case ADMIN = 10;
    case CUSTOMER = 50;
}

protected $casts = [
    'roles' => UserRole::class . ':collection',
];

namespace App\Enums;

use Illuminate\Contracts\Database\Eloquent\Castable;

enum UserRole: int implements Castable
{
    use BaseEnum;
    
    case ADMIN = 10;
    case CUSTOMER = 50;
}