Download the PHP package wardenyarn/model-properties without Composer
On this page you can find all versions of the php package wardenyarn/model-properties. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download wardenyarn/model-properties
More information about wardenyarn/model-properties
Files in wardenyarn/model-properties
Package model-properties
Short Description Add properties to your Laravel model
License MIT
Homepage https://github.com/wardenyarn/model-properties
Informations about the package model-properties
Laravel Model Properties
Simple model properties implementation.
Problem
Imagine, you have a Page model with given schema
But then, you might decide to add a meta_title property. Or another bunch of properties, that might be useful for just one or two pages. In the end, we will see something like that:
Solution
To avoid extending of original table, we can use a one-to-one relation. But you will need to create additional table for every model with Properties. So, we might just use a polymorphic relation for properties and models.
This package is made to simplify this polymorphic relation setup.
Installation
You can install the package via composer:
Usage
First we need to publish a properties table and migrate it.
Second, we need to add HasProperties
trait and fill protected $properties
property.
And lastly, execute artisan properties:fill command, that will persist properties from
model $properties
into DB;
Access to properties
Just use $model->properties
attribute to access to Properties object, that contains all the stuff.
Saving
Set properties values by $model->properties->property_name
or using $model->properties->set()
method.
It also works with new model instances:
Note: in this case only $model->save()
method will save properties.
Cast
Property values will be automatically casted by Laravel.
Available casts:
- array
- boolean
- collection
- date
- datetime
- immutable_date
- immutable_datetime
- double
- float
- integer
- real
- string
- timestamp
If you need access to casted properties right after saving, you need to fresh()
model before use.
Default values
You can define a default value for property
Caching
Property values are cached forever with first access to properties
attribute, so the database load won't be an issue.
Cache will be refreshed with saving of properties or model.
You can always clear all of the Laravel cache by artisan command
Config
You can change config after importing it with given artisan command:
Testing
License
The MIT License (MIT). Please see License File for more information.
Laravel Package Boilerplate
This package was generated using the Laravel Package Boilerplate.