Package Data | |
---|---|
Maintainer Username: | sdavis1902 |
Maintainer Contact: | s.davis1902@gmail.com (Scott Davis) |
Package Create Date: | 2017-07-27 |
Package Last Update: | 2023-06-06 |
Language: | PHP |
License: | MIT |
Last Refreshed: | 2024-11-16 15:00:44 |
Package Statistics | |
---|---|
Total Downloads: | 6,272 |
Monthly Downloads: | 125 |
Daily Downloads: | 2 |
Total Stars: | 1 |
Total Watchers: | 1 |
Total Forks: | 1 |
Total Open Issues: | 0 |
Add ability to save additional fields or Vars on a Laravel model without a specific db column for it
Via Composer
$ composer require sdavis1902/eloquent-vars
Add the service provider ( not required for 5.5 )
sdavis1902\EloquentVars\EloquentVarsServiceProvider::class,
Publish and run migration
$ php artisan vendor:publish --provider="sdavis1902\EloquentVars\EloquentVarsServiceProvider"
$ php artisan:migrate
Add the trait to your model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use sdavis1902\EloquentVars\EloquentVarsTrait;
class Task extends Model {
use EloquentVarsTrait;
Now you can do the following...
$task->setVar('temporary_field', 'The value');
$task->setVar('temporary_id', 1);
echo $task->getVar('temporary_field');
$task->deleteVar('temporary_field');
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.
// 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.
$tasks = \App\Task::with('ModelVars')->get();
foreach($tasks as $task){
if($task->vars->first_var){
echo $task->vars->first_var;
}
}
Note, values are stored as a string, so if you save an int, when you get it, it will be a string.
Please see CONTRIBUTING and CONDUCT for details.
The MIT License (MIT). Please see License File for more information.