Laravel Tests, Model Arrays and Appended Attributes

Problem:

After creating "appended" columns in a Laravel model, tests that converted that model to an array (or JSON) began to fail as they were trying to insert the appended column to the database.

UGH - Quick Fix Please:

Before converting your model toJSON or toArray, use the makeHidden('appended_column_name') option to hide any specific appended columns.

OK Keep Talking.

In my template, I have three models that have images associated with them.  Instead of hard coding the route for the image, I have employed the use of an appended attribute.  This is one that is created on the model that is in addition to the columns within the database. You can read more about appended attributes here.

This means instead of coding "/path/to/image/image.png", I can just call model->image_url. BOSS.  Ok.

In my Unit Tests, I have created several helper functions that make live easier overall when creating the tests themselves.  For example, in my "CompanyTest", I have a function that creates a company, and I call this from other functions where I need a default company created.

1. The make is a helper function that just returns a factory created model of the class passed in.2. When posting to /admin/companies, I pass in the $company->toArray, which automatically passes in all the values needed to save it to the database.

1. The make is a helper function that just returns a factory created model of the class passed in.

2. When posting to /admin/companies, I pass in the $company->toArray, which automatically passes in all the values needed to save it to the database.

After making my "appends" change, tests that used this helper function no longer passed.  Specifically, I received the following message:

appends2.png

When converting a model toArray() or toJson(), any appended values are also included.  This means that when I passed the array(ed?) model to the post endpoint, it tried to insert the image_url field into the database.  As that column does not exist, the insert failed.

WHAT TO DO? Hide That Attribute, Yo!

It's possible to hide specific attributes prior to converting the model to an array.  You can read more about that here.  Once I made the change, all tests passed again (whew).

append3.png