Laravel Attributes Package
Last updated on by Eric L. Barnes
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 is the creator of Laravel News and has been covering Laravel since 2012.