/laravel-dynamic-attributes

A package for adding dynamic attributes to Laravel's Eloquent Models.

Primary LanguagePHP

Laravel Dynamic Attributes

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');