Optimizing CRUD operations: inserting data into a database

In many applications, create-read-update-delete (CRUD) operations are common tasks that are regularly performed. To optimize your workflow and keep your code clean, it is a good idea to generalize these operations. When you build a webapplication from scratch, you likely have written some wrapper functions for this purpose, but when you are using Laravel, a lot of nice features are available out of the box. In this blog, we focus on the creation of new records and the modification of existing ones.

Manually inserting records

There are basically two ways to insert or update records in the database: manually or via mass assignment. To manually insert a record, you first create an instance of the corresponding model, then you add the relevant information and last you save the model. For example, you have a website where new customers are able to create an account. They have to fill in a form with the following information: name, emailaddress, date of birth and company they work for. After submitting the form, you have to save the information to the database:

$customer = new Customer;
$customer->name = Input::get(‘name’);
$customer->company = Input::get(‘company’);
$customer->date_of_birth = Input::get(‘date_of_birth’);
$customer->email = Input::get(‘email’);
$customer->save();

Updating an existing customer works in a similar way. Instead of creating a new model, an existing model is grabbed from the database:

$customer = Customer::find($id);
or
$customer = Customer::findOrFail($id);

The latter one throws an exception in case the customer cannot be found.

Mass assignment

The method described above is a rather save way to create a record or update an existing one. However, if a customer has a lot of different properties to store in de database, the code may become quite long. Mass assignment, in which an array is passed directly to a create method, may be a good option:

Customer::create([
   ‘name’ => Input::get(‘name’),
   ‘company’ => Input::get(‘company’),
   ‘date_of_birth’ => Input::get(‘date_of_birth’),
   ‘email’ => Input::get(‘email’)
]);

To simplify matters even more, the full Input array can be passed to the create method, resulting in very clean code:

Customer::create(Input::all());

Updating the details of existing customer goes in a similar way:

$customer = Customer::find($id)
$customer->update(Input::all());

Guarded in protected fillables

Although mass assignment results in very clean code, it comes with a potential security risk. What if a bad willing person hacks the input form and adds an additional field, for example customer_privileges, and then submits the form? The update method simply uses all of the submitted inputs, including the field added by the hacker, resulting in changed priveleges.

To avoid this kind of abuse, Laravel makes use of the variables $guarded and $fillable. Your mass assignment calls will only works if one of these variables is specified in the corresponding model. In the $guarded variable, the database columns that should NOT be mass assigned are specified (black list). In the $fillable variable, columns that are mass assignable are listed (white list).

Mutators

Quite often you want data to be of a specific format before saving it to the database. A common example is dates: the user likes to see a date as mm/dd/yyyy, but the database needs yyyy-mm-dd. The mutators in Laravel are very useful for this job. You have to add the mutator to the corresponding model. In our example, we have to save the date of birth in the customers table, so we add the following method to the customers model:

public function setDateOfBirthAttribute ($date)
{
   $this->attributes[‘date_of_birth’] = 
      Carbon::createFromFormat(‘d/m/Y’,$date)->toDateString();
}

The name of the function consists of three parts. The first one is ‘set’ (there is also a get variant which is used when reading data from the database). The second part is the name of the database column, where underscores are replaced by camel case. The last part is ‘attribute’. Now, each time date of birth is saved to the database, this automatically will be in the correct format.

As long as you follow the naming convention above, mutators can be used on any type of data. You only have to write a function to convert the incoming data to the correct format and pass it to the attributes array.

Summary

Creating new records or updating existing ones is easy in the Laravel framework. These operations can be done manually or via mass assignment. When using mass-assignment, don’t forget to specificy either the $guarded variable or the $fillable variable in the corresponding model, otherwise it won’t work. Last, mutators are quite nice to make sure information is send to the database in the correct format. Before user input is stored in the database, it should be validated. Validation of user input is not this discussed in this blog, but the subject of the next one.


Mijn Twitter profiel Mijn Facebook profiel
Leonie Derendorp Webdeveloper and co-owner of PLint-sites in Sittard, The Netherlands. I love to create complex webapplications using Laravel! Latest post
Transitions in Vue

Leave a Reply

Your email address will not be published. Required fields are marked *