blog

  • Home
  • blog
  • PHP Fractal – Make Your API’s JSON Pretty, Always!

PHP Fractal – Make Your API’s JSON Pretty, Always!

If you’ve built an API before, I’ll bet you’re used to dumping data directly as a response. It may not be harmful if done right, but there are practical alternatives that can help solve this small problem.

One of the available solutions is Fractal. It allows us to create a new transformation layer for our models before returning them as a response. It’s very flexible and easy to integrate into any application or framework.

Image of fractals with PHP embedded in them

Installation

We will be using a Laravel 5.3 app to build an example and integrate the Fractal package with it, so go ahead and create a new Laravel app using the installer or via Composer.

laravel new demo

or

composer create-project laravel/laravel demo

Then, inside the folder, we require the Fractal package.

composer require league/fractal

Creating the Database

Our database contains a users and roles table. Every user has a role, and each role has a list of permissions.

// app/User.php

class User extends Authenticatable
{
    protected $fillable = [
        'name',
        'email',
        'password',
        'role_id',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * @return IlluminateDatabaseEloquentRelationsBelongsTo
     */
    public function role()
    {
        return $this->belongsTo(Role::class);
    }
}
// app/Role.php

class Role extends Model
{
    protected $fillable = [
        'name',
        'slug',
        'permissions'
    ];

    /**
     * @return IlluminateDatabaseEloquentRelationsHasMany
     */
    public function users()
    {
        return $this->hasMany(User::class);
    }
}

Continue reading %PHP Fractal – Make Your API’s JSON Pretty, Always!%

LEAVE A REPLY