PHPackages                             twithers/laravel-php-attributes - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. twithers/laravel-php-attributes

ActiveLibrary

twithers/laravel-php-attributes
===============================

Use PHP 8 Attributes easily inside of your Laravel application

2.0.0(9mo ago)31.7k4[1 issues](https://github.com/TWithers/laravel-php-attributes/issues)MITPHPPHP ^8.0CI passing

Since Sep 20Pushed 9mo ago1 watchersCompare

[ Source](https://github.com/TWithers/laravel-php-attributes)[ Packagist](https://packagist.org/packages/twithers/laravel-php-attributes)[ Docs](https://github.com/twithers/laravel-php-attributes)[ RSS](/packages/twithers-laravel-php-attributes/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (7)Dependencies (3)Versions (9)Used By (0)

laravel-php-attributes
======================

[](#laravel-php-attributes)

[![Latest Version on Packagist](https://camo.githubusercontent.com/1b6bb28d8094fe2b1b3aa5be9f0441c43a5ae64a46a9db60d8c39af1a4b4a726/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f74776974686572732f6c61726176656c2d7068702d617474726962757465732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/twithers/laravel-php-attributes)[![Tests](https://github.com/TWithers/laravel-php-attributes/workflows/Tests/badge.svg)](https://github.com/TWithers/laravel-php-attributes/workflows/Tests/badge.svg)

This package will help you create and use your own PHP 8 Attributes inside of a Laravel application without having to worry about writing your own loaders, reflection methods, and data caching.

By default, all attributes in your `app` directory are automatically loaded and cached, with an accessor provided to look up attributes as needed. The package can be configured to limit directories as well as attributes to speed up loading and minimize caching.

- [Installation](#installation)
- [PHP 8 Attributes Overview](#attributes-in-php-8)
- [Usage](#usage)
    - [AttributeCollection Facade](#accessing-the-attributecollection-api)
    - [AttributeTarget API](#attributetarget-api)
    - [Standalone Usage](#standalone-usage)
- [Commands](#clearing-attribute-cache)
- [Testing](#testing)
- [Contributing](#contributing)
- [License Information](#license)

Installation
------------

[](#installation)

Require this package with composer using the following command:

```
composer require twithers/laravel-php-attributes
```

You can publish the config file with:

```
php artisan vendor:publish --provider="TWithers\LaravelAttributes\AttributesServiceProvider" --tag="config"
```

These are the contents of the published config file:

```
return [

    /**
     * Caching will make use of Laravel's built-in file caching. Using caching will be a massive performance benefit
     * as no directories and files need to be scanned for attributes and attribute usages
     */
    'use_cache' => true,

    /**
     * By default this will scan your listed directories below for all attributes and then search for them.
     *
     * If you want to avoid the initial search, you can list your attribute classes below:
     *     'App\Attributes\Foo',
     *     App\Attributes\Bar::class,
     *
     */
    'attributes' => [

    ],

    /**
     * By default this will scan all files inside your app folder for attributes.
     *
     * If you want to limit the folders, you can adjust the namespace and the files:
     * 'App\Http\Controllers' => app_path('Http/Controllers')
     */
    'directories' => [
        'App' => app_path(),
    ],

];
```

You can disable caching, but it is not recommended as each request would scan for and establish the attribute collection.

You can limit attributes to a specific list by declaring them. The empty array indicates that ALL attributes found in the listed directories will be scanned for.

You can narrow down the directory search, or list multiple separate directories to find attributes and their usage. Ensure your array is structured with `$namespace => $directoryPath` to ensure files are correctly found and accessed.

Attributes in PHP 8
-------------------

[](#attributes-in-php-8)

First attributes are defined and namespaced. An `Attribute` attribute is then applied to it. After defining an attribute, we can then add it to anything we want: classes, methods, functions, properties, etc. Below is a example of how you would define and use an attribute.

```
#[Attribute]
class SampleAttribute
{
    public string $name;
    public string $label;

    public function __construct(
        string $name,
        string $label
    ){
        $this->name = name;
        $this->label = label;
    }
}

#[SampleAttribute(name: 'SampleClass', label: 'My Sample Class Label')]
class SampleClass
{
    #[SampleMethod(name: 'sampleMethod', label: 'My Sample Method Label')]
    public function sampleMethod(): bool
    {
        return true;
    }
}
```

We have a defined attribute `SampleAttribute` that requires a `name` and a `label`. We have a `SampleClass` that uses that attribute, as well as the method `sampleMethod()` that also uses that attribute.

### Looking up Attributes in PHP 8+

[](#looking-up-attributes-in-php-8)

Attributes by themselves do nothing. PHP currently doesn't give you a super easy way to capture attributes and values. You are left using PHP Reflection, which may not be something you have ever used. Reflection is just that, reflecting on the code. You pass in some information, such as class names, methods names, etc, and the Reflection API will give you all the info you need to know about it... including attributes.

Below is how you would currently use the Reflection API to look up attributes.

```
$reflectionClass = new ReflectionClass(SampleClass::class);
$attributes = $reflectionClass->getAttributes(SampleMethod::class);
if (count($attributes)){
    $attribute = $attributes[0]->newInstance();
    dump($attribute->name); // "SampleClass"
    dump($attribute->label); // "My Sample Class Label"
}

$reflectionClass = new ReflectionClass(SampleClass::class);
$reflectionMethod = $reflectionClass->getMethod('sampleMethod');
$attributes = $reflectionMethod->getAttributes(SampleMethod::class);
if (count($attributes)){
    $attribute = $attributes[0]->newInstance();
    dump($attribute->name); // "Sample Method"
    dump($attribute->label); // "My Sample Method"
}
```

This isn't much code to write and pretty easy to follow. If you are using attributes throughout your application, however, you will soon find yourself repeating this code in many places.

**Enter Laravel PHP Attributes**

Usage
-----

[](#usage)

### Accessing the AttributeCollection API

[](#accessing-the-attributecollection-api)

This package provides the `Attributes` facade to help you access the stored attribute collection data after it is processed. You can also type-hint the `AttributeCollection` class throughout your app and Laravel will autoload the initialized attribute collection.

The `Attributes` facade and `AttributeCollection` provides the following useful methods:

```
Attributes::findByClass(string $className): ?AttributeTarget
Attributes::findByClassMethod(string $className, string $methodName): ?AttributeTarget
Attributes::findByClassProperty(string $className, string $propertyName): ?AttributeTarget
Attributes::findTargetsWithAttribute(string $attributeName): AttributeTarget[]
```

An `AttributeTarget` is the class, method, or property that the attribute is attached to. The `AttributeTarget` has the following structure:

- **int $type**: Indicates if the target is a class, method, or property
- **string $className**: The full namespaced name of the class that was targeted or contains the attribute
- **?string $identifier**: The name of the method or property
- **allAttributes(): AttributeInstance\[\]**: The method to retrieve a list of all attached attributes (`$name` and instantiated `$instance`)

Here is how the code from above could be rewritten:

```
$attributes = Attributes::findByClass(SampleClass::class)->allAttributes();
dump($attributes[0]->instance->name); // "SampleClass"
dump($attributes[0]->instance->label); // "My Sample Class Label"

$attributes = Attributes::findByClassMethod(SampleClass::class, 'sampleMethod')->allAttributes();
dump($attributes[0]->instance->name); // "Sample Method"
dump($attributes[0]->instance->label); // "My Sample Method"
```

### AttributeTarget API

[](#attributetarget-api)

The `AttributeTarget` class exposes a few helpful methods as well for finding specific attributes:

```
AttributeTarget::allAttributes(): AttributeInstance[]
AttributeTarget::hasAttribute(string $attributeName): bool
AttributeTarget::findByName(string $attributeName): AttributeInstance[]
```

### Standalone Usage

[](#standalone-usage)

If you do not want to utilize the Laravel service provider's automatic loading and caching of attributes, you can remove it from the list of loaded service providers. You will be able to use the `AttributeAccessor` class to look up attributes if you know the pertinent info. Here are the methods that are available:

```
AttributeAccessor::forClass(string $className): ?AttributeInstance[]
AttributeAccessor::forClassMethod(string $className, string $methodName): ?AttributeInstance[]
AttributeAccessor::forClassProperty(string $className, string $propertyName): ?AttributeInstance[]
```

If the class, method, or property are not found, it will return `null`, otherwise, each of those static functions will look up all attached attributes and return an array of `AttributeInstances` which have both the `$name` and `$instance` of the attribute for your use.

Clearing Attribute Cache
------------------------

[](#clearing-attribute-cache)

By default, attributes will be found and processed, with the results cached on the first request. Subsequent requests will utilize the cached data to avoid costly processing time. This means that changes to attributes or methods that are using attributes will require the cache to be cleared. By default (unless your environment is set to store files in a different location), the cached file is stored in `bootstrap\cache\attributes.php` and can be manually deleted. You can also use the following command:

```
php artisan attributes:clear
```

It would be pertinent to use this command in your deployment process to ensure any added attributes will be properly cached.

Testing
-------

[](#testing)

```
./vendor/bin/phpunit
```

Contributing
------------

[](#contributing)

All contributions are welcome.

### Thank you!

[](#thank-you)

[![](https://camo.githubusercontent.com/759c568c448393b7e783b51b58d783e693c64555246bb1d984fad0129f1b3381/68747470733a2f2f636f6e747269622e726f636b732f696d6167653f7265706f3d74776974686572732f6c61726176656c2d7068702d61747472696275746573)](https://github.com/twithers/laravel-php-attributes/graphs/contributors)Made with [contrib.rocks](https://contrib.rocks).

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance49

Moderate activity, may be stable

Popularity22

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 95.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~148 days

Recently: every ~258 days

Total

8

Last Release

292d ago

Major Versions

0.2.0 → 1.0.02022-09-24

1.0.4 → 2.0.02025-07-24

### Community

Maintainers

![](https://www.gravatar.com/avatar/bd175d4344ddd15f8ee1292dec770ebc47185fd4b7539170ca45093db47a96cb?d=identicon)[TWithers](/maintainers/TWithers)

---

Top Contributors

[![TWithers](https://avatars.githubusercontent.com/u/943772?v=4)](https://github.com/TWithers "TWithers (43 commits)")[![nexxai](https://avatars.githubusercontent.com/u/4316564?v=4)](https://github.com/nexxai "nexxai (1 commits)")[![toddstoker](https://avatars.githubusercontent.com/u/248347?v=4)](https://github.com/toddstoker "toddstoker (1 commits)")

---

Tags

attributesphp8-attributesphp-attributeslaravel-php-attributeslaravel-php8-attributesattribute-caching

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/twithers-laravel-php-attributes/health.svg)

```
[![Health](https://phpackages.com/badges/twithers-laravel-php-attributes/health.svg)](https://phpackages.com/packages/twithers-laravel-php-attributes)
```

###  Alternatives

[jetbrains/phpstorm-attributes

PhpStorm specific attributes

41416.0M647](/packages/jetbrains-phpstorm-attributes)[vormkracht10/laravel-mails

Laravel Mails can collect everything you might want to track about the mails that has been sent by your Laravel app.

24149.7k](/packages/vormkracht10-laravel-mails)[thettler/laravel-console-toolkit

This Package provides some usefully console features like the attribute syntax for arguments and options, validation, auto ask and casting.

324.1k](/packages/thettler-laravel-console-toolkit)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
