supportpal/eloquent-model
Eloquent-style base Model for PHP/Laravel to build custom, non-database models. Supports accessors/mutators, attribute casting, guarded/fillable and hidden fields, appended attributes, and easy array/JSON conversion.
Installation:
composer require jenssegers/model
Add the namespace to your composer.json under autoload.psr-4:
"Jenssegers\Model": "vendor/jenssegers/model/src"
Basic Model Setup:
Extend Jenssegers\Model\Model in your custom model:
use Jenssegers\Model\Model;
class User extends Model
{
protected $fillable = ['name', 'email'];
}
First Use Case: Instantiate and populate a model:
$user = new User(['name' => 'John Doe', 'email' => 'john@example.com']);
$user->save(); // Override with custom logic (e.g., API call)
src/Jenssegers/Model/Model.php for core logic (e.g., save(), toArray()).Data Handling:
protected $fillable = ['name', 'email'];
protected $guarded = ['password']; // Blocks unless in $fillable
protected $casts = [
'is_active' => 'boolean',
'created_at' => 'datetime:Y-m-d'
];
Custom Logic:
save() for non-DB storage (e.g., API calls):
public function save()
{
$response = API::post('/users', $this->toArray());
$this->id = $response['id'];
return $this;
}
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
Serialization:
hidden/visible/appends:
protected $hidden = ['password'];
protected $appends = ['full_name'];
API facade with your HTTP client (e.g., Guzzle).Validator or Respect/Validation) before save().hasMany via array properties):
public function orders()
{
return collect($this->orders)->map(fn($order) => new Order($order));
}
No Database Abstraction:
save()/find() is manual.Attribute Casting Timing:
getAttribute(), not during initialization.public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->birthday = $this->asDateTime($this->birthday);
}
Hidden Attributes Leak:
hidden attributes may still appear in debug output (e.g., dd($model)).toArray() to filter:
public function toArray()
{
return array_diff_key($this->attributesToArray(), array_flip($this->hidden));
}
getAttributes() to inspect raw data:
dd($model->getAttributes());
toJson(): Add debug info:
public function toJson($options = 0)
{
return json_encode([
'data' => parent::toJson($options),
'meta' => ['casts' => $this->casts]
], $options);
}
Custom Serialization:
Extend toArray()/toJson() for nested structures:
public function toArray()
{
return [
'id' => $this->id,
'metadata' => $this->getMetadataArray()
];
}
Event System:
Add hooks (e.g., beforeSave):
public function save()
{
$this->fireModelEvent('beforeSave');
// ... custom logic ...
$this->fireModelEvent('saved');
return $this;
}
Macros: Dynamically add methods:
Model::macro('replicateWithout', function ($attributes) {
$model = clone $this;
unset($model->{$attributes});
return $model;
});
How can I help you explore Laravel packages today?