V
V
Vasyl Fomin2017-08-24 17:48:12
API
Vasyl Fomin, 2017-08-24 17:48:12

What is the correct way to return JSON from Laravel controllers for application API?

I develop applications with RESTFull API on Laravel. Advise how it would be more correct to implement formatting and returning data in JSON format from Laravel controllers?
Most of the tutorials I've seen just returned a model:

public function show($id)
{
   $post =  \App\Models\Post::findOrFail($id);
   return $post;
}

As a result, we get a JSON array at the front:
{
    "id": 1,
    "name": "Пример статьи",
    "slug": "primer,
    "body":"",
    "category_id":1
    "created_at": "2017-08-23 14:26:41",
    "updated_at": "2017-08-23 14:26:41",
    "deleted_at": null,  
}

They also do this:
public function create(Request $request)
{
   //...
   return response()->json(['success' => true, 'data' = 'Данные успешно сохранены']);
}

Problems and questions with this approach:
1. In most cases, on the frontend, we do not need to show all the fields of the table (category_id, updated_at, deleted_at,...). Each time manually an array in each controller, it seems to me not quite right ...
2. What if we need, for example, to extract all comments for articles (only also without extra fields)
3. We need to extract all categories -> their articles - > their comments
4. It is necessary to deduce certain fields in a certain format, for example date.
To work with data, I use the "repository" pattern. On the frontend, for the time being, it is planned to have a site on vue.js.
Maybe someone uses the spatie/laravel-fractal package , what would be the feedback, recommendations.
I would like to see a good example of the development of such systems and what tools are used there.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alex Wells, 2017-08-24
@fomvasss

I am using laravel-fractal. In the latest version of league/fractal, on the basis of which spatie/fractalistic is built, they added the primitive type and everything fell into place.
Of course, it was not without dancing with a tambourine: I made the Transform trait for the necessary models, which adds the toApi method (although it would be better to call it transform), which takes the class from the $transformer variable:
And I had to write a macro for the Laravel collection, also toApi (). Although both of these features can be dispensed with using fractal($items, $transformer).
The rest is completely satisfied.

K
Konstantin B., 2017-08-24
@Kostik_1993

1. In order for some fields of the model not to be displayed, you need to use the hidden variable, using it we indicate which fields should not be displayed in the JSON response.

protected $hidden = [
        'type_id',
        'created_at',
        'updated_at',
    ];

2. For each model, you must specify your fields that should be hidden
protected $hidden = [
        'type_id',
        'created_at',
        'updated_at',
    ];

3. 4. There are also special variables and methods for this. This method is also availableCategory::with('posts.comments')->get();
public function getDateAttribute () {
        return date('Y-M-D', $this->date);
    }
public function getUrlAttribute () {
        return url($this->slug);
    }

this method will output $post->date in the required format in
order for such a method to be available in json, you need to specify it in
protected $appends = [
        'url',
        'topic',
    ];

A
artemmityushov, 2017-08-26
@artemmityushov

Both proposed options have their pros and cons. I would add a 3rd output option through Formatters, we mainly use it, at least to control exactly what comes to the api.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question