llanfair
llanfair

Reputation: 1885

Laravel - Modifying data for API only for convenience

Let's assume the following data that is exactly being returned like it's stored into database:

[
    {
        "user_name": "User 1",
        "photo_file": "user1.jpg"
    },
    {
        "user_name": "User 2",
        "photo_file": "user2.jpg"
    }
    // ...
]

I want to use this data in a JavaScript application but I'd like to append a full path of the user's photo, like doing a treatment for the data before returning it to the API. How can I do that using Laravel?

Upvotes: 0

Views: 207

Answers (3)

Jakub Kratina
Jakub Kratina

Reputation: 664

If you are building Laravel API, sure, as Matthew said, go and check Fractal. But don't forget to Dingo, the best tool for building API at Laravel. And it uses Fractal too.

Upvotes: 1

Matthew Daly
Matthew Daly

Reputation: 9476

I assume at present you're just converting the results of your query into JSON and returning that. This works, but it does mean the response is tightly coupled to your database structure, which is a bad idea. Ideally you should have a layer of abstraction to handle adding and formatting data, kind of like a view layer in MVC.

There are plenty of solutions for this. I use Fractal for my Laravel API's. It allows you to easily customise the output of a particular endpoint by specifying a transformer that will render that object for you. That way you can easily choose the data to display and format it how you wish.

Upvotes: 1

DevK
DevK

Reputation: 9952

Accessors are good for this.

Let's assume your data is stored in a model called Customer. I would write an accessor like this:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{

    protected $appends = ['photo_file']; // In order to see the new attribute in json dumps

    public function getPhotoPathAttribute()
    {
        $name = $this->getAttribute('photo_file');

        if(!isset($name))
            return null;

        return '/full/path/to/image/' . $name;
    }
}

This way you can now call $customer->photo_path and it will return `/full/path/to/image/image_name.jpg' (or null if the attribute is not set).

Edit:

In order to show this attribute in jsons (without specifically calling $model->photo_path) you will also need to add protected $appends = ['photo_file'] to the model (updated).

I would recommend against overriding original name (so I leave photo_file attribute untouched).

Upvotes: 1

Related Questions