aw-studio/laravel-dynamic-attributes

v0.1.0 2021-10-20 08:44 UTC

This package is auto-updated.

Last update: 2024-11-05 18:49:45 UTC


README

A package for adding dynamic attributes to Elqouent Models.

See also: Laravel Dynamic Relations

Setup

Install the package via composer:

composer require aw-studio/laravel-dynamic-attributes

Publish the migrations:

php artisan vendor:publish --tag="dynamic-attributes:migrations"

Usage

Just add the HasDynamicAttributes to a Model:

use Illuminate\Database\Eloquent\Model;
use AwStudio\DynamicAttributes\HasDynamicAttributes;

class Page extends Model
{
    use HasDynamicAttributes;
}

And voila:

$page = Page::create([
    'headline' => 'Hello World!',
    'text'     => 'Lorem Ipsum...',
]);

echo $page->headline; // "Hello World!"

Set Attribute Cast Manually

Usually casts should be set correctly depending on the attribute value:

Page::create(['released_at' => now()->addWeek()]);

dd($page->released_at); // Is an instance of Illuminate\Support\Carbon

However you may want to set an attribute cast manually:

$page = Page::create(['is_active' => 1]);

dump($page->is_active); // output: 1

$page->setDynamicAttributeCast('is_active', 'boolean')->save();

dd($page->is_active); // output: true

Query Scopes

Page::whereAttribute('foo', 'bar');