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 →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article