This package provides the ability to create custom attributes for Laravel controllers. You can use these attributes to add functionality like authorization, validation, or any other custom behavior to your controller methods.
jojomak13/laravel-attributes is a Laravel package for this package provides the ability to create custom attributes for laravel controllers. you can use these attributes to add functionality like authorization, validation, or any other custom behavior to your controller methods..
It currently has 5 GitHub stars and 4 downloads on Packagist (latest version v1.0.0).
Install it with composer require jojomak13/laravel-attributes.
Discover more Laravel packages by jojomak13
or browse all Laravel packages to compare alternatives.
Last updated
This package provides the ability to create custom attributes for Laravel controllers. You can use these attributes to add functionality like authorization, validation, or any other custom behavior to your controller methods.
composer require jojomak13/laravel-attributes
Let's walk through creating a custom attribute for authorization using Laravel policies.
First, generate a new attribute class using the provided artisan command:
php artisan make:attribute PolicyAttribute
This will create a new attribute class in the App\Attributes namespace.
Each attribute class contains two main methods:
__construct: Defines the parameters you want to pass to your attributehandle: Contains the logic for your attribute's functionalityHere's an example of implementing a policy-based authorization attribute:
<?php
namespace App\Attributes;
use Attribute;
use Illuminate\Support\Facades\Gate;
use Joseph\Attributes\Concerns\ICustomAttribute;
#[Attribute(Attribute::TARGET_METHOD)]
class PolicyAttribute implements ICustomAttribute
{
public function __construct(string $ability, $arguments = [])
{
$this->ability = $ability;
$this->arguments = $arguments;
}
public function handle(string $ability, $arguments = [])
{
Gate::authorize($ability, $arguments);
}
}
To use attributes in your controllers, follow these steps:
HasAttributes traitHere's an example:
<?php
namespace App\Http\Controllers;
use App\Attributes\PolicyAttribute;
use App\Models\Post;
use Illuminate\Routing\Controller;
use Joseph\Attributes\Traits\HasAttributes;
class PostController extends Controller
{
use HasAttributes;
#[PolicyAttribute('viewAny', Post::class)]
public function index()
{
return 'posts here';
}
}
In this example, the PolicyAttribute will check if the current user has permission to view posts before executing the index method.
HasAttributes trait is required for attribute functionalityICustomAttribute interfaceFor more advanced usage and additional examples, please refer to the package documentation.