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 {}
##Getting an attribute
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;
##Checking for an attribute
Use has() to check if a class has a specific attribute:
Attributes::has(User::class, Description::class);
Attributes::has(User::class, SomeOtherAttribute::class);
##Repeated attributes
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;
$tags[1]->name;
##Without an attribute filter
All class-level methods also accept an optional attribute parameter. When omitted, they work with any attribute:
Attributes::get(User::class);
Attributes::has(User::class);
Attributes::getAll(User::class);
##Using object instances
All methods accept either a class string or an object instance:
$user = new User();
Attributes::get($user, Description::class);
Attributes::has($user, Description::class);