Use #[Config], #[CurrentUser], and #[RouteParameter] attributes to inject configuration and contextual parameters directly into service constructors.
Traditionally, injecting primitive values (like API keys or base URLs) into service classes required writing manual $this->app->when(...)->needs(...)->give(...) bindings in AppServiceProvider.
Modern Laravel supports contextual dependency injection attributes directly on constructor parameters.
Injecting Configuration with #[Config]
namespace App\Services;
use Illuminate\Container\Attributes\Config;
class StripePaymentGateway
{
public function __construct(
#[Config('services.stripe.secret')]
protected string $secretKey,
#[Config('services.stripe.currency', 'usd')]
protected string $currency
) {}
}
Injecting the Authenticated User with #[CurrentUser]
namespace App\Services;
use App\Models\User;
use Illuminate\Container\Attributes\CurrentUser;
class UserAuditLogger
{
public function __construct(
#[CurrentUser]
protected ?User $actor
) {}
}
Summary
- Eliminates verbose contextual bindings in
AppServiceProvider. - Works on controller actions, service classes, and job constructors.
- Native PHP attributes:
#[Config],#[CurrentUser],#[RouteParameter],#[Storage].
Related Tips
View all tips →Use Laravel's remember_token as a Revocation Signal
Use Laravel's remember_token as an invalidation signal for saved account-switching state without maintaining a dedicated token or revocation table.
Extract Dominant Colors and Handle HEIC/AVIF Images in Laravel 13.24
Laravel 13.24 adds dominantColor() to the Image API for extracting the primary color of an image, plus native support for HEIC and AVIF formats.