๐ŸŽ‰๐ŸŽ‰ Larasense is officially launched ๐ŸŽ‰๐ŸŽ‰
- Your Hub for Laravel News, Trends & Updates

Complete Guide to Laravel and Livewire PHP Attributes (23 Attributes)

laravel
livewire
attributes
Nabil Hassen
Nabil Hassen
Dec 19, 2024
23 Laravel & Livewire PHP Attributes
Last updated on Dec 19, 2024
Table of contents:

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:

1. #[Auth]

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,
) {
//
}
}

2. #[Cache]

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,
) {
//
}
}

3. #[Config]

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,
) {
//
}
}

4. #[CurrentUser]

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
}
}

5. #[DB]

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
}
}

6. #[Log]

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
}
}

7. #[RouteParameter]

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,
) {
//
}
}

8. #[Storage]

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
) {
//
}
}

9. #[Tag]

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:

1. Computed

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.

2. Isolate

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.

3. Js

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.

4. Layout

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.

5. Lazy

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.

6. Locked

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.

7. Modelable

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;
}

8. On

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.

9. Reactive

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++;
}
}

10. Renderless

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.

11. Rule

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.

12. Session

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.

13. Title

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".

14. Url

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.

Nabil Hassen
Nabil Hassen
Full Stack Web Developer

Stay Updated.

I'll you email you as soon as new, fresh content is published.

Thanks for subscribing to my blog.

Latest Posts

Larasenes Logo
Larasense
Stay updated on Laravel news, trends, and updates with curated content from top blogs, YouTube, and podcasts in a sleek, user-friendly design.