sdavis1902/eloquent-vars
| Install | |
|---|---|
composer require sdavis1902/eloquent-vars |
|
| Latest Version: | v2.0.2 |
| PHP: | ^8.1 |
| License: | MIT |
| Last Updated: | Sep 18, 2025 |
| Links: | GitHub · Packagist |
Eloquent Vars
Add ability to save additional fields or Vars on a Laravel model without a specific db column for it
Install
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
Usage
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.
Contributing
Please see CONTRIBUTING and CONDUCT for details.
Credits
License
The MIT License (MIT). Please see License File for more information.
Related Packages
In Laravel 5.3 Route::controller was removed. This package replaces that functi...
laravel-paypalpayment is simple package help you process direct credit card paym...
Powerful PHP database abstraction layer (DBAL) with many features for database s...