let’s think about what we want as a result.

Actually, when you create a new model, you can quickly pass its attributes using the constructor:


$user = new User([
  'first_name' => 'Francesco',
  'last_name' => 'Malatesta'

These parameters are passed from the constructor to another method called fill():

   * Create a new Eloquent model instance.
   * @param  array  $attributes
   * @return void

  public function __construct(array $attributes = array())



As a logical consequence, if we want to implement this Auto Hydrate feature, we will have to write a new constructor to deal with the auto hydrating there and then to call the parent class. So, let’s go back to our AweloquentModel class. Here’s the first implementation:


namespace App\Aweloquent;

use Illuminate\Database\Eloquent\Model;

class AweloquentModel extends Model {

  public function __construct(array $attributes = [])
    $attributes = $this->autoHydrate($attributes);


  private function autoHydrate(array $attributes)
    // getting the request instance using the service container
    $request = app('Illuminate\Http\Request');

    // getting the request form data, except the token
    $requestData = $request->except('_token');

    foreach($requestData as $name => $value)
      // manually specified attribute has priority over auto- 
	  hydrated one.
      $attributes[$name] = $value;

    return $attributes;

The autoHydrate method creates the following:

  • An instance of the current request to get the required data
  • After that, and for each cycle, it adds to the attributes array every element in the request data array (excluding the CSRF '_token')

Note that the explicit specified attribute (the one you can put in the Model constructor) has the priority over the request data array. So, you are still free to deal with the Model and decide what to define and what not, maybe to add some extra data that you are not getting from the form.

If you try to create a new user by setting up a basic form, the Auto Hydrate feature is already working.