Complete Guide to Laravel and Livewire PHP Attributes (23 Attributes)
In modern PHP development, attributes provide a structured way to add metadata to classes, methods, and properties. Both Laravel and Livewire have embraced this feature, introducing several attributes to streamline common tasks. Let's explore the PHP attributes provided by Laravel's Container and Livewire, along with examples for each.
Laravel Container Attributes
Laravel's service container includes attributes that simplify dependency resolution and service injection:
#[Auth]
1. Injects the authentication manager into a class.
Example:
use Illuminate\Container\Attributes\Auth;use Illuminate\Contracts\Auth\Guard; class PhotoController extends Controller{ public function __construct( #[Auth('web')] protected Guard $auth, ) { // }}
#[Cache]
2. Injects the cache manager into a class.
Example:
use Illuminate\Container\Attributes\Cache;use Illuminate\Contracts\Cache\Repository; class PhotoController extends Controller{ public function __construct( #[Cache('redis')] protected Repository $cache, ) { // }}
#[Config]
3. Injects configuration values directly into class dependencies.
Example:
use Illuminate\Container\Attributes\Config; class PhotoController extends Controller{ public function __construct( #[Config('app.timezone')] protected string $timezone, ) { // }}
#[CurrentUser]
4. Injects the currently authenticated user.
Example:
use Illuminate\Container\Attributes\CurrentUser;use App\Models\User; class PhotoController extends Controller{ public function __construct( #[CurrentUser] User $currentUser ) { // $currentUser is the authenticated user instance }}
#[DB]
5. Injects a specific database connection.
Example:
use Illuminate\Container\Attributes\DB;use Illuminate\Database\Connection; class PhotoController extends Controller{ public function __construct( #[DB('mysql')] protected Connection $connection, ) { // $db is the 'mysql' database connection }}
#[Log]
6. Injects the logger instance into a class.
Example:
use Illuminate\Container\Attributes\Log;use Psr\Log\LoggerInterface; class PhotoController extends Controller{ public function __construct( #[Log('daily')] protected LoggerInterface $log, ) { // $logger is the logger instance }}
#[RouteParameter]
7. Injects a route parameter into a class.
Example:
use App\Models\Photo;use Illuminate\Container\Attributes\RouteParameter; class PhotoController extends Controller{ public function __construct( #[RouteParameter('photo')] protected Photo $photo, ) { // }}
#[Storage]
8. Injects the storage manager into a class.
Example:
use Illuminate\Container\Attributes\Storage;use Illuminate\Contracts\Filesystem\Filesystem; class PhotoController extends Controller{ public function __construct( #[Storage('local')] protected Filesystem $filesystem ) { // }}
#[Tag]
9. Tags a service for later retrieval.
Example:
use Illuminate\Container\Attributes\Tag; class PhotoController extends Controller{ public function __construct( #[Tag('reports')] protected iterable $reports, ) { // ... }}
Livewire Attributes
Livewire introduces several attributes to enhance component functionality:
Computed
1. The #[Computed]
attribute is a way to create "derived" properties in Livewire. Like accessors on an Eloquent model, computed properties allow you to access values and cache them for future access during the request.
Example:
use Livewire\Attributes\Computed; class UserProfile extends Component{ public $firstName; public $lastName; #[Computed] public function getFullName() { return "{$this->firstName} {$this->lastName}"; }}
In this example, getFullName
is a computed property that combines firstName
and lastName
.
Isolate
2. By using Livewire's #[Isolate] class attribute, you can mark a component as "isolated". This means that whenever that component makes a server roundtrip, it will attempt to isolate itself from other component requests.
Example:
use Livewire\Attributes\Isolate; #[Isolate]class TodoList extends Component{ }
This is useful if the update is expensive and you'd rather execute this component's update in parallel with others.
Js
3. The #[Js]
attribute is used to bind a JavaScript property directly to the component.
Example:
use Livewire\Attributes\Js; class NotificationComponent extends Component{ #[Js] public $isVisible = true;}
This property can now be used directly in the JavaScript side of the application to show or hide notifications.
Layout
4. The #[Layout]
attribute specifies the layout file that should be used by the component.
Example:
use Livewire\Attributes\Layout; #[Layout('layouts.dashboard')]class Dashboard extends Component{ }
This would instruct Livewire to render the component within the dashboard
layout.
Lazy
5. Lazy-loaded components aren't full loaded until they enter the browser's viewport, for example when a user scrolls to one.
Example:
use Livewire\Attributes\Lazy; #[Lazy]class UserProfile extends Component{ //}
In this case, the $profileData
property will not be loaded until it's actually needed.
Locked
6. The #[Locked]
attribute prevents a property from being modified by the frontend.
Example:
use Livewire\Attributes\Locked; class UserSettings extends Component{ #[Locked] public $userId;}
In this example, the $userId
property cannot be updated from the frontend.
Modelable
7. The #[Modelable]
attribute is used bind only one child component property from its parent component.
Example:
use Livewire\Attributes\Modelable; class PostForm extends Component{ #[Modelable] public $title;}
On
8. The #[On]
attribute binds an action or method to a specific event.
Example:
use Livewire\Attributes\On; class UserRegistered extends Component{ #[On('userRegistered')] public function handleNewUser($user) { // Handle the registration event }}
In this example, the method handleNewUser
will be called when the userRegistered
event is triggered.
Reactive
9. The #[Reactive]
attribute marks a property as reactive, meaning any child component properties will automatically update on the frontend when something in the parent component changes.
Example:
use Livewire\Attributes\Reactive; class Counter extends Component{ #[Reactive] public $count = 0; public function increment() { $this->count++; }}
Renderless
10. The #[Renderless]
attribute is used to indicate that a component does not render any view, but it can be used for logic purposes.
Example:
use Livewire\Attributes\Renderless; class FormLogic extends Component{ #[Renderless] public function validateForm() { // Perform form validation logic }}
This class will not render any view but can handle the form validation logic.
Rule
11. The #[Rule]
attribute is used to define custom validation rules on component properties.
Example:
use Livewire\Attributes\Rule; class RegisterUser extends Component{ #[Rule('required|string|max:255')] public $username;}
This will enforce a validation rule on the $username
property.
Session
12. The #[Session]
attribute binds a component property to the session.
Example:
use Livewire\Attributes\Session; class UserProfile extends Component{ #[Session] public $theme;}
This stores the $theme
property in the session so it persists across requests.
Title
13. The #[Title]
attribute allows you to specify the title of the componentโs view.
Example:
use Livewire\Attributes\Title; #[Title('My Custom Page Title')]class PageTitle extends Component{ public function render() { return view('page'); }}
This will set the page's title to "My Custom Page Title".
Url
14. The #[Url]
attribute binds a property to the URL.
Example:
use Livewire\Attributes\Url; class Navigation extends Component{ #[Url] public $currentUrl = '';}
This makes the $currentUrl
property automatically reflect the URL of the current page.
Conclusion
With 23 PHP attributes in Laravel and Livewire, developers have a wide range of tools to simplify workflows, improve code clarity, and leverage modern PHP practices. These attributes reduce boilerplate and bring expressive, declarative coding to your applications.
Stay Updated.
I'll you email you as soon as new, fresh content is published.