spatie/php-attribute-reader
Lightweight PHP 8+ utility to read native attributes from classes, methods, properties, and parameters using reflection. Designed for simple, fast attribute discovery in frameworks and libraries, with an API that fits common annotation-style workflows.
All examples on this page use the following attribute and class:
#[Attribute]
class Description
{
public function __construct(
public string $text,
) {}
}
#[Description('A user account')]
class User {}
Use get() to retrieve a single attribute instance from a class. Returns null if the attribute is not present.
use Spatie\Attributes\Attributes;
$description = Attributes::get(User::class, Description::class);
$description->text; // 'A user account'
Use has() to check if a class has a specific attribute:
Attributes::has(User::class, Description::class); // true
Attributes::has(User::class, SomeOtherAttribute::class); // false
If an attribute is marked as IS_REPEATABLE, use getAll() to retrieve all instances. Returns an empty array when no matching attributes exist.
#[Attribute(Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)]
class Tag
{
public function __construct(public string $name) {}
}
#[Tag('featured')]
#[Tag('popular')]
class Post {}
$tags = Attributes::getAll(Post::class, Tag::class);
$tags[0]->name; // 'featured'
$tags[1]->name; // 'popular'
All class-level methods also accept an optional attribute parameter. When omitted, they work with any attribute:
Attributes::get(User::class); // first attribute, regardless of type
Attributes::has(User::class); // true if the class has any attribute
Attributes::getAll(User::class); // all attributes on the class
All methods accept either a class string or an object instance:
$user = new User();
Attributes::get($user, Description::class);
Attributes::has($user, Description::class);
How can I help you explore Laravel packages today?