PHPackages                             innoscience/eloquental - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. innoscience/eloquental

ActiveLibrary[Database &amp; ORM](/categories/database)

innoscience/eloquental
======================

A rather clever model for Laravel's Eloquent ORM with self-validation, ordering, and query control.

3384PHP

Since Apr 9Pushed 12y ago3 watchersCompare

[ Source](https://github.com/innoscience/eloquental)[ Packagist](https://packagist.org/packages/innoscience/eloquental)[ RSS](/packages/innoscience-eloquental/feed)WikiDiscussions master Synced 2d ago

READMEChangelogDependenciesVersions (1)Used By (0)

Eloquental
==========

[](#eloquental)

Its eloquental my dear Watson! A rather clever model for Laravel's Eloquent ORM with self-validation, ordering, and query control.

Inspired by Ardent and Eloquent.

[![Build Status](https://camo.githubusercontent.com/a795c63508ee85092438f45ea86d7f9f7eea3ea393f13874a891cc4e6478329c/68747470733a2f2f7472617669732d63692e6f72672f696e6e6f736369656e63652f656c6f7175656e74616c2e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/innoscience/eloquental)

[![Scrutinizer Code Quality](https://camo.githubusercontent.com/2f015d1817a956d6386ba7279bd5c1c47fcbd9f6d8271e8a5a62e2bd3c880f2d/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f696e6e6f736369656e63652f656c6f7175656e74616c2f6261646765732f7175616c6974792d73636f72652e706e673f733d39666439393361663730633431343539343736343233326233353066396431353330313361303935)](https://scrutinizer-ci.com/g/innoscience/eloquental/)

Copyright (C) 2014 Brandon Fenning

Obligations
-----------

[](#obligations)

Tested &amp; Compatible with PHP 5.3+

Requires Laravel 4.1

Instatement
-----------

[](#instatement)

Add `innoscience/eloquental` to the `composer.json` file:

```
"require": {
    "innoscience/eloquental": "dev-master"
}

```

After this, run `composer update` to install the package

A Brief Overview
----------------

[](#a-brief-overview)

Eloquental is namespaced to `Innoscience\Eloquental`, below is a rather elemental example of a Eloquental model using conditional validation in conjunction with the model's validation events:

```
use Innoscience\Eloquental\Eloquental;

class News extends Eloquental {
	var $table = 'news';
	var $orderBy = array('date' => 'desc');
	var $rules = array(
			'title'=>'required',
			'slug'=>'required|unique:news,slug',
			'date'=>'required|date',
			'article'=>'required|min:50'
	);
}

News::validating(function($model){
	$model->getValidator()->sometimes('slug', 'required|unique:news,slug,'.$model->id, function($model) {
		return $model->exists;
	});
});

News::validated(function($model){
	// # Do some awesome validated stuff here that I can't think of at the moment
});

// # Elsewhere, our models initiated, the latent eloquental power is harnessed...

$model = new Article(array(
		'title'=>'Case Files',
		'date'=>'1889-10-01',
		'slug'=>'case-files',
		'article'=>'My notes are as follows...'));

if (!$model->save()) {
	return Redirect::back()->withErrors($model->errors());
}

```

The Natural Ordering of Things
------------------------------

[](#the-natural-ordering-of-things)

Eloquental has a built in ordering property that if set, will automatically invoke `orderBy()` by default on queries:

> Note: This functionality currently does not work for the $query-&gt;lists() method

```
News extends Eloquental {
	...
	var $orderBy = array('date' => 'desc');
}

```

### Bring order to order

[](#bring-order-to-order)

Add as many ordering clauses as you wish in `$field => $direction` pairs

```
User extends Eloquental {
	...
	var $orderBy = array(
		'lastname' => 'asc',
		'firstname' => 'asc'
	);
}

```

> **Fun fact**: If you add an `->orderBy()` clause when querying a model, the model's `->orderBy` property will be ignored when generating the query. This is made possible with a new `Builder` provided by Eloquental that allows the orderBy clause to be added conditionally at the end of the query building process. Later on the documentation will demonstrate how you can add similar custom functionality to your models.

Validate This My Good Sir
-------------------------

[](#validate-this-my-good-sir)

### Basics

[](#basics)

Eloquental has a built in rules set and the ability to add rules on the fly as required.

```
Article extends Eloquental {
	...
	var $rules = array(
		'title'=>'required'
	);
}

$model = new Article(array('title'=>'Case Files'));
if (!$model->save()) {
	return Redirect::back()->withErrors($model->errors());
}

// Or validate the model without saving

if (!$model->validate()) {
	return Redirect::back()->withErrors($model->errors());
}

```

> **Fun Fact**: If `$rules` are not set, neither the `->validate()` method nor the `::validating` or `::validated` events will fire for the model.

### Validation Events

[](#validation-events)

Eloquental models have two validation events that are fired during saving:

```
User::validating(function($model) {
	$model->getValidator()->sometimes('password', 'required|min:8|confirmed', function($model) {
		return ($model->password && $model->isDirty('password')) ? TRUE : FALSE;
	});
});

User::validated(function($model) {
	// # Validated stuff goes here
});

```

### Skip Validation

[](#skip-validation)

Sometimes you may wish a model to skip validation:

```
$model->skipValidation()->save();

```

As soon as the `->save()` method is invoked on a model, the `skipValidation` flag returns to `FALSE`. Subsequent saves will be validated unless `skipValidation()` is invoked.

### Validation Errors

[](#validation-errors)

If a model fails validation, the errors are accessible via the `->errors()` method which returns a `MessageBag` from Laravel:

```
if (!$model->save()) {
	echo $model->errors()->all(':message');
}

```

### Manual Validation

[](#manual-validation)

```
if (!$model->validate()) {
	echo $model->errors()->all(':message');
}

```

### Manual Validation with override rules

[](#manual-validation-with-override-rules)

```
$rules = array('title'=>required');

$customMessages = array('title'=>'This be required');

if (!$model->validate($rules, $customMessages)) {
	echo $model->errors()->all(':message');
}

```

> Note: Setting the `$rules` or `$customMessages` properties when calling `$model->validate($rule = array(), $customMessages = array())` will override the model's default rules and reset the validation instance.

### Manipulate the Validator instance

[](#manipulate-the-validator-instance)

If you wish to manipulate the `Validator` instance, you can easily do so:

```
$model = News::find(1);
$model->getValidator()->sometimes('author', 'required', function($model) {
    return $model->published == 1;
});

```

### Set the Validator instance

[](#set-the-validator-instance)

```
$model->setValidator(Validator::make($rules, $messages));

```

Auto-Purge Feckless Data
------------------------

[](#auto-purge-feckless-data)

In combination with the validation mechanism, auto-purge allows attributes to be passed to the model and disposed of before saving:

```
User extends Eloquental {
	...
	var $autoPurge = array('password_confirmation');
}

```

This will cause the `password_confirmation` attribute to be purged from the attributes of the model before saving.

> **Fun Fact**: Auto-purged properties are last accessible in the `::validated()` event as they are purged right before the save event fires. If the `$autoPurge` property is not populated, auto-purge is not applied.

A Timely Builder of Queries
---------------------------

[](#a-timely-builder-of-queries)

The query builder event is a powerful mechanism that allows you to insert query clauses conditionally just before the query builder is executed. The `->orderBy` mechanism in Eloquental is an implementation of this functionality. Other uses include conditionally showing models based on authentication status, etc. It should be used with care.

> **Fun fact**: If an `->orderBy()` clause is added during the `buildingQuery` event, this will cause the `$model->orderBy` property to be ignored.

The Query Builder event is invoked similarly to model events except passing the query object via the `buildingQuery` static method.

#### Example for showing only published content to guest users

[](#example-for-showing-only-published-content-to-guest-users)

```
News::buildingQuery(function($query) {
	if (!Auth::check()) {
		return $query->where('published', 1);
	}

	return $query;
});

```

The method must return either `FALSE`, `$query` or an instance of `Illuminate\Database\Query\Builder`.

> Note: This functionality currently does not work for the $query-&gt;lists() method

Notorized in the Trial of Testing
---------------------------------

[](#notorized-in-the-trial-of-testing)

Eloquental is fully unit tested. Tests are located in the `tests` directory of the Eloquental package and can be run with `phpunit` in the package's base directory.

Licensed to all Honorable Personages
------------------------------------

[](#licensed-to-all-honorable-personages)

Eloquental is licensed under GPLv2

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity16

Limited adoption so far

Community5

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/1737fa1e0d9eeac8c269552378baae6b17f491b20290da29d69f6575574d794a?d=identicon)[innoscience](/maintainers/innoscience)

### Embed Badge

![Health badge](/badges/innoscience-eloquental/health.svg)

```
[![Health](https://phpackages.com/badges/innoscience-eloquental/health.svg)](https://phpackages.com/packages/innoscience-eloquental)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[mongodb/mongodb

MongoDB driver library

1.6k64.0M546](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90340.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
