Laravel's Contextual Attributes
Are you tired of constantly fetching the current user with request()->user()
, auth()->user()
or passing the Request
object to every controller method that needs it?
Laravel 11, with its continued support for PHP 8.1's attribute syntax, offers a more streamlined approach: by simply using the #[CurrentUser]
attribute, you can directly inject the authenticated user into your controller methods:
use App\Models\User;
use Illuminate\Container\Attributes\CurrentUser;
class AuthController
{
public function me(#[CurrentUser] User $user): User
{
return $user;
}
}
A Deeper Dive: Contextual Attributes
Beyond injecting the current user, Laravel's contextual attribute feature allows you to inject various data (such as driver implementations or configuration values) from the IoC container directly into your class methods. This approach can simplify your code and enhance its readability.
To explore the full range of available attributes and their potential applications, refer to the official GitHub pull request:
And if you didn't know, there's a whole world of other attributes waiting to be discovered! This blog post focused on contextual attributes, namely CurrentUser
, but for all the available PHP attributes you can use in your Laravel project, check out this blog post: