medalink/laravel-reflects-constants

A small helper package that aids in the retrieval of class constants of models in laravel.
3,615
Install
composer require medalink/laravel-reflects-constants
Latest Version:v2.2.1
PHP:^7.2.5|^8.0.2
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

oriceon/toastr-5-laravel

Easy toastr notifications for Laravel 5

503,999 79
php-tmdb/laravel

Laravel Package for TMDB ( The Movie Database ) API. Provides easy access to the...

53,312 160
oriceon/oauth-5-laravel

OAuth Service Provider for Laravel 5

1,669,304 173
artdarek/oauth-4-laravel

OAuth Service Provider for Laravel 4

522,424 677
narutimateum/toastr-5.2-laravel

toastr.js for Laravel 5.2 easy notification like growl for example

37,567 13