• Reading time ~ 1 min
  • 28.01.2025

The article "Laravel Attributes Overview: What and How to Use" decried the possibility of simplifying dependency injection with attributes. However, it is not necessary to limit yourself to only standard Laravel attributes. You can create your own attribute that will perform the task you want.

An example of creating an attribute that automatically pulls values from the configuration, i.e. to be similar to a helper config():

First, let's create a class MyConfigthat implements the interface Illuminate\Contracts\Container\ContextualAttribute. This is necessary for the container to work with it.

namespace App\Attributes;
use Attribute;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Container\ContextualAttribute;
#[Attribute(Attribute::TARGET_PARAMETER)]
class MyConfig implements ContextualAttribute
{
    public function __construct(
        public string $key,
    ) {}
    public static function resolve(self $attribute, Container $container)
    {
        return $container->make('config')->get($attribute->key);
    }
}

Now the attribute #[MyConfig] is ready. Use it, for example, to automatically substitute the application name in the controller:

namespace App\Http\Controllers;
use App\Attributes\MyConfig;
class ExampleController extends Controller
{
    public function __construct(
        #[MyConfig('app.name')] protected string $appName
    ) {}
    public function show(): string
    {
        return "Имя приложения: {$this->appName}";
    }
}

Of course, Laravel already has the , Configbut the main thing is that this example is easy to adapt to other tasks, such as substitution of API keys, flags, etc.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297

We shoot down "Shahed" drones every day. Each one downed means lives saved. But we need mobility: a van or a trailer. Every donation = another night under protection.

🚐 Van fundraiser for my unit, 1020 regiment 🎯 Goal: 500,000 ₴
🔗 Donation link 💳 4441 1111 2546 4663