Laravel Packages

Laravel Attributes Package

Published
Laravel Attributes Package image

If you ever need to create attributes on a model, the Laravel Attributes package is designed to make this easy.

To give you an example of attributes, pretend you have an e-commerce store and want to associate technical details with a product. With this package, you can do it like this:

First, add the Attributable trait to the model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Milwad\LaravelAttributes\Traits\Attributable;

class Product extends Model
{
    use HasFactory, Attributable;
}

Then, create a new product and attach attributes to it:

$product = Product::query()->create([
    'name' => 'iPad',
    'content' => 'text',
]);

$data = [
    [
        'title' => 'display',
        'value' => '10.2‑inch Retina display',
    ],
    [
        'title' => 'capacity',
        'value' => '64GB, 256GB',
    ],
    [
        'title' => 'height',
        'value' => '9.8 inches',
    ],
    [
        'title' => 'width',
        'value' => '6.8 inches',
    ],
];

$product->attachAttributes($data);

Once this is saved, you can then pull out all the attributes like this:

$product = Product::query()->with('attributes')->get();

$product->attributes

For more details check out the package on GitHub.

Eric L. Barnes photo

Eric is the creator of Laravel News and has been covering Laravel since 2012.

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux image

pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux

Read article
Laranon: Reversible PII Anonymization for Laravel and LLMs image

Laranon: Reversible PII Anonymization for Laravel and LLMs

Read article
PHP 8.6 is released!  image

PHP 8.6 is released!

Read article
Laravel Warrant: Row-Level Permissions With Eloquent image

Laravel Warrant: Row-Level Permissions With Eloquent

Read article
JSON Schema Validation Rules and a RetryFor Attribute in Laravel 13.43 image

JSON Schema Validation Rules and a RetryFor Attribute in Laravel 13.43

Read article
Durable Workflow: Long-Running Workflows for Laravel image

Durable Workflow: Long-Running Workflows for Laravel

Read article