what is Auto Hydrate in laravel

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:

<?php

$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())
  {
    $this->bootIfNotBooted();

    $this->syncOriginal();

    $this->fill($attributes);
  }

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:

<?php

namespace App\Aweloquent;

use Illuminate\Database\Eloquent\Model;

class AweloquentModel extends Model {

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

    parent::__construct($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.
      if(!isset($attributes[$name]))
      $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.

Recommended :  Integrate sweetAlert in laravel 5.1

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

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares