Skip to main content

One post tagged with "resources"

View All Tags

Enhanced Resources for Laravel

· 3 min read
Connor Tumbleson
Director of Engineering
Jason Jones
Senior Software Engineer II, Lead

Developing an API was a common task for engineers working with Laravel in the early days of the framework. Prior to version 5.5 Laravel did not offer an elegant way to format/prepare API responses. Historically, it worked by calling toArray() on your model instance.

This pattern of calling toArray() risked the possibility of exposing attributes that should not be exposed over an API. As a result, it was common to use the $hidden property to exclude the specified attributes during serialization which was helpful in building an API response as both a mechanism to avoid exposing sensitive data and more generally controlling which data would be included. The example shown below was a common pattern prior to Laravel 5.5.

<?php

class User extends Eloquent {
protected $hidden = ['password', 'remember_token'];
}

// Usage
$user = User::find(1);
$user->toArray();
// Returns: ['name' => 'John', 'email' => 'john@example.com']

This approach was flexible, but any change to your database schema resulted in those changes appearing in your API. We needed something more concrete and landed on Fractal which served us well until Laravel added official support for API Resources, and thus we worked on an enhancement for that feature.