medalink/laravel-reflects-constants

A small helper package that aids in the retrieval of class constants of models in laravel.
3,619
Install
composer require medalink/laravel-reflects-constants
Latest Version:v2.2.1
PHP:^7.2.5|^8.0.2
Laravel:6 – 10
License:MIT
Last Updated:Aug 31, 2023
Links: GitHub  ·  Packagist
Maintainer: Medalink

laravel-reflects-constants

A small helper package that aids in the retrieval of class constants of models.

composer require medalink/laravel-reflects-constants

How to use

Let's assume you have a class with defined constants for different types.

<?php
class ProductInformation
{
    use \Medalink\Reflects\Constants;

    /**
    * Optional constant blacklist, anything in here will be filtered
    */
    public $reflectedConstantsBlacklist = [
        'TEST',
    ];

    const TYPE_OVERVIEW = 'OVERVIEW';
    const TYPE_SAFETY = 'SAFETY';
    const TYPE_WARRANTY = 'WARRANTY';
    const TYPE_PRODUCT_INFO = 'PRODUCT_INFO';
    const TEST = 'TEST';
}

This package will allow you to return these constants as a human readable array. This is most useful when using this data in various places through your application. Let's take a look at using this package to help a factory choose a random type.

$factory->define(ProductInformation::class, function (Faker $faker) {
    return [
        'type' => $faker->randomElement(ProductInformation::getReflectedConstants('TYPE_')),
    ];
});

The resulting array would look like this:

$types = ProductInformation::getReflectedConstants('TYPE_');

$types = [
    'Overview',
    'Safety',
    'Warranty',
    'Product Info'
];

Let's take a look at using this to populate a laravel nova options dropdown.

Select::make('Type')
    ->options(ProductInformation::getReflectedConstants('TYPE_'))
    ->sortable(),

The getReflectedConstants supports a blacklist, a prefix, returning the prefix with the constant name, and a human readable toggle. Take a look at the source for more details on how to use these features.

Related Packages

valorin/random

Random is a simple helper package designed to make it easy to generate a range o...

413,065 233
php
cline/variable-keys

Laravel Blueprint macros for variable primary key and morph types

22,912 0
php
cline/struct

Lean, attribute-driven Laravel data objects with explicit validation and Eloquen...

17,788 0
php
cline/toggl

Advanced feature flag management with strategies, time bombs, and groups

12,171 0
php
cline/sequencer

Sequential migration and operation orchestration for Laravel

11,143 0
php

Version History

Version Released PHP Laravel License
v2.2.1 ^7.2.5|^8.0.2 ^6.0|^7.0|^8.0|^9.0|^10.0 MIT
v2.2.0 ^7.2.5|^8.0.2 ^6.0|^7.0|^8.0|^9.0 MIT
v2.1.0 ^7.2.5|^8.0 ^6.0|^7.0|^8.0 MIT
v2.0.1 ^7.2.5 ^6.0|^7.0|^8.0 MIT
v2.0.0 ^7.2.5 ^6.0|^7.0 MIT