Self-validating, secure and smart models for Laravel's Eloquent ORM
Self-validating, secure and smart models for Laravel's Eloquent ORM
Self-validating smart models for Laravel Framework 5's Eloquent ORM.
Based on the Aware bundle for Laravel 3 by Colby Rabideau.
Copyright (C) 2013-2015 Max Ehsan & Igor Santos
Visit our Releases list. The changelog is made there :)
Add laravelbook/ardent as a requirement to composer.json (see our latest stable version on the badges!):
{
"require": {
"laravelbook/ardent": "3.*"
}
}Update your packages with composer update or install with composer install.
You can also add the package using composer require laravelbook/ardent and later specifying the version you want (for now, dev-master is your best bet).
If you're want to use Ardent as a standalone ORM package you're invited to do so by using the following configuration in your project's boot/startup file (changing the properties according to your database, obviously):
\LaravelArdent\Ardent\Ardent::configureAsExternal(array(
'driver' => 'mysql',
'host' => 'localhost',
'port' => 3306,
'database' => 'my_system',
'username' => 'myself',
'password' => 'h4ckr',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci'
), 'en'); //English is the default messages language, may be left emptyHow often do you find yourself re-creating the same boilerplate code in the applications you build? Does this typical form processing code look all too familiar to you?
…Implementing this yourself often results in a lot of repeated boilerplate code. As an added bonus, you controllers (or route handlers) get prematurely fat, and your code becomes messy, ugly and difficult to understand.
What if someone else did all the heavy-lifting for you? What if, instead of regurgitating the above mess, all you needed to type was these few lines?...
Route::post('register', function() {
$user = new User;
if ($user->save()) {
return Redirect::to('/')->with('message', 'Thanks for registering!');
} else {
return Redirect::to('/')->withErrors($user->errors());
}
}
);Enter Ardent!
Ardent - the magic-dust-powered, wrist-friendly, one-stop solution to all your dreary input sanitization boilerplates!
Puns aside, input validation functionality can quickly become tedious to write and maintain. Ardent deals away with these complexities by providing helpers for automating many repetitive tasks.
Ardent is not just great for input validation, though - it will help you significantly reduce your Eloquent data model code. Ardent is particularly useful if you find yourself wearily writing very similar code time and again in multiple individual applications.
For example, user registration or blog post submission is a common coding requirement that you might want to implement in one application and reuse again in other applications. With Ardent, you can write your self-aware, smart models just once, then re-use them (with no or very little modification) in other projects. Once you get used to this way of doing things, you'll honestly wonder how you ever coped without Ardent.
No more repetitive brain strain injury for you!
Ardent aims to extend the Eloquent base class without changing its core functionality. Since Ardent itself is a descendant of Illuminate\Database\Eloquent\Model, all your Ardent models are fully compatible with Eloquent and can harness the full power of Laravels awesome OR/M.
To create a new Ardent model, simply make your model class derive from the Ardent base class. In the next examples we will use the complete namespaced class to make examples cleaner, but you're encouraged to make use of use in all your classes:
use LaravelArdent\Ardent\Ardent;
class User extends Ardent {}Note: You can freely co-mingle your plain-vanilla Eloquent models with Ardent descendants. If a model object doesn't rely upon user submitted content and therefore doesn't require validation - you may leave the Eloquent model class as it is.
Ardent models use Laravel's built-in Validator class. Defining validation rules for a model is simple and is typically done in your model class as a static variable:
class User extends \LaravelArdent\Ardent\Ardent {
public static $rules = array(
'name' => 'required|between:3,80|alpha_dash',
'email' => 'required|between:5,64|email|unique:users',
'password' => 'required|min:6|confirmed',
'password_confirmation' => 'required|min:6',
);
}Note: you're free to use the array syntax for validation rules as well. I hope you don't mind the old Laravel docs link, but as good as Laravel documentation is, clear reference on pipe/array syntaxes for Validation rules is unfortunately gone since 5.1.
Ardent models validate themselves automatically when Ardent->save() is called.
$user = new User;
$user->name = 'John doe';
$user->email = '[email protected]';
$user->password = 'test';
$success = $user->save(); // returns false if model is invalidNote: You can also validate a model at any time using the
Ardent->validate()method.
When an Ardent model fails to validate, a Illuminate\Support\MessageBag object is attached to the Ardent object which contains validation failure messages.
Retrieve the validation errors message collection instance with Ardent->errors() method or Ardent->validationErrors property.
Retrieve all validation errors with Ardent->errors()->all(). Retrieve errors for a specific attribute using Ardent->validationErrors->get('attribute').
Note: Ardent leverages Laravel's MessagesBag object which has a simple and elegant method of formatting errors.
There are two ways to override Ardent's validation:
forceSave() validates the model but saves regardless of whether or not there are validation errors.
both Ardent->save($rules, $customMessages) and Ardent->validate($rules, $customMessages) take two parameters:
$rules is an array of Validator rules of the same form as Ardent::$rules.$customMessages parameter (same as Ardent::$customMessages)An array that is not empty will override the rules or custom error messages specified by the class for that instance of the method only.
Note: the default value for
$rulesand$customMessagesis emptyarray(); thus, if you pass anarray()nothing will be overriden.
Just like the Laravel Validator, Ardent lets you set custom error messages using the same syntax.
class User extends \LaravelArdent\Ardent\Ardent {
public static $customMessages = array(
'required' => 'The :attribute field is required.',
...
);
}You can create custom validation rules the same way you would for the Laravel Validator.
Ardent provides some syntatic sugar over Eloquent's model events: traditional model hooks. They are an easy way to hook up additional operations to different moments in your model life. They can be used to do additional clean-up work before deleting an entry, doing automatic fixes after validation occurs or updating related models after an update happens.
All before hooks, when returning false (specifically boolean, not simply "falsy" values) will halt the operation. So, for example, if you want to stop saving if something goes wrong in a beforeSave method, just return false and the save will not happen - and obviously afterSave won't be called as well.
Here's the complete list of available hooks:
before/afterCreate()before/afterSave()before/afterUpdate()before/afterDelete()before/afterValidate() - when returning false will halt validation, thus making save() operations fail as well since the validation was a failure.For example, you may use beforeSave to hash a users password (actually, it would be a better idea to use auto-hashing!):
class User extends \LaravelArdent\Ardent\Ardent {
public function beforeSave() {
// if there's a new password, hash it
if($this->isDirty('password')) {
$this->password = Hash::make($this->password);
}
return true;
//or don't return nothing, since only a boolean false will halt the operation
}
}beforeSave and afterSave can be included at run-time. Simply pass in closures with the model as argument to the save() (or forceSave()) method.
$user->save(array(), array(), array(),
function ($model) { // closure for beforeSave
echo "saving the model object...";
return true;
},
function ($model) { // closure for afterSave
echo "done!";
}
);Note: the closures should have one parameter as it will be passed a reference to the model being saved.
Have you ever written an Eloquent model with a bunch of relations, just to notice how cluttered your class is, with all those one-liners that have almost the same content as the method name itself?
In Ardent you can cleanly define your relationships in an array with their information, and they will work just like if you had defined them in methods. Here's an example:
class User extends \LaravelArdent\Ardent\Ardent {
public static $relationsData = array(
'address' => array(self::HAS_ONE, 'Address'),
'orders' => array(self::HAS_MANY, 'Order'),
'groups' => array(self::BELONGS_TO_MANY, 'Group', 'table' => 'groups_have_users')
);
}
$user = User::find($id);
echo "{$user->address->street}, {$user->address->city} - {$user->address->state}";The array syntax is as follows:
No open issues yet, or sync has not completed.