A package for adding dynamic attributes to Elqouent Models.
See also: Laravel Dynamic Relations
Install the package via composer:
composer require aw-studio/laravel-dynamic-attributes
Publish the migrations:
php artisan vendor:publish --tag="dynamic-attributes:migrations"
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!"
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
Page::whereAttribute('foo', 'bar');