Eloquent Vars
![Software License][ico-license]
![Total Downloads][ico-downloads], (*1)
Add ability to save additional fields or Vars on a Laravel model without a specific db column for it, (*2)
Install
Via Composer, (*3)
``` bash
$ composer require sdavis1902/eloquent-vars, (*4)
Add the service provider ( not required for 5.5 )
``` php
sdavis1902\EloquentVars\EloquentVarsServiceProvider::class,
Publish and run migration
``` bash
$ php artisan vendor:publish --provider="sdavis1902\EloquentVars\EloquentVarsServiceProvider"
$ php artisan:migrate, (*5)
## Usage
Add the trait to your model
``` php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use sdavis1902\EloquentVars\EloquentVarsTrait;
class Task extends Model {
use EloquentVarsTrait;
Now you can do the following..., (*6)
``` php
$task->setVar('temporary_field', 'The value');
$task->setVar('temporary_id', 1);, (*7)
echo $task->getVar('temporary_field');, (*8)
$task->deleteVar('temporary_field');, (*9)
Note, the above require the model object to have an id, so will need to have been written to the database already.
If you want use a more eloquent method, you can use the following. Additionally, the following method will work on new model instances that have not been inserted yet.
``` php
// saving new model and it's vars all at once
$task = new \App\Task;
$task->name = 'Some Task';
// now our vars
$task->vars->first_var = 'test';
$task->save();
// retreiving a model and accessing it's vars directly
$task = \App\Task::find(1);
echo $task->vars->first_var;
// save another var
$task->vars->second_var = 'another test';
$task->save();
// if you try to get a var that doesn't exist, it simply returns null
var_dump($task->vars->no_var);
Additionally, the trait includes a relationship for the vars which allows you to eager load. The above method of accessing vars uses this relationship, so you can eager load and then use the vars like above., (*10)
``` php
$tasks = \App\Task::with('ModelVars')->get();, (*11)
foreach($tasks as $task){
if($task->vars->first_var){
echo $task->vars->first_var;
}
}
```, (*12)
Note, values are stored as a string, so if you save an int, when you get it, it will be a string., (*13)
Contributing
Please see CONTRIBUTING and CONDUCT for details., (*14)
Credits
License
The MIT License (MIT). Please see License File for more information., (*15)