V
V
vostotskiy2017-08-28 15:44:55
JSON
vostotskiy, 2017-08-28 15:44:55

How to return json or view with the necessary data for each CRUD method in the Laravel controller?

Hello. I am implementing a restful controller for working with some entity, namely the post, get, put, patch, delete methods, and, accordingly, auxiliary ones for displaying forms: show, edit.
I wanted to make sure that each method returns, depending on the "accept" header, the required view with data or json (if the header is equal to "application / json") for REST API requests.
To do this, I made a middleware, where using the
$request->wantsJson() method it
is checked whether the presence of resp. header, and if it is, then variables are pulled from the view object and encoded in json, which is given to the client.
But there is a drawback in my approach, when, for example, after the deletion has occurred, I would like to send a message and a 204 code in the case of a REST API.
But for the view, in theory, you need to redirect to the main page, and changing 204 to 302 does not work.
Please tell me how to organize the controller in such a way that it would give json with the desired status and give a view or make a redirect after updating, deleting, adding.
ps. Perhaps you need to inject the response into the controller methods and check the header type in each individual action, and depending on them, do a redirect or return json with the necessary code?
psps. Perhaps this is wrong, but I would make a separate controller for the API, and a separate one for "browser" work. but that's how the task was set for me.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
artemmityushov, 2017-08-28
@artemmityushov

There will be many special cases in this approach, so the universal duck will not work, it’s better to check and return what you need in each method.
We also wanted to make it universal before, but during the life of the project everything changed so that universality became the Achilles' heel.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question