Answer the question
In order to leave comments, you need to log in
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;
}
{
"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,
}
public function create(Request $request)
{
//...
return response()->json(['success' => true, 'data' = 'Данные успешно сохранены']);
}
Answer the question
In order to leave comments, you need to log in
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.
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',
];
protected $hidden = [
'type_id',
'created_at',
'updated_at',
];
Category::with('posts.comments')->get();
public function getDateAttribute () {
return date('Y-M-D', $this->date);
}
public function getUrlAttribute () {
return url($this->slug);
}
protected $appends = [
'url',
'topic',
];
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 questionAsk a Question
731 491 924 answers to any question