Answer the question
In order to leave comments, you need to log in
How to correctly return a response from controller methods using the REST API methodology?
Good day. After reading many articles on REST Api on Laravel, confusion appeared in my head. Please help clarify one question. Let's say I have a User entity and I want to get, delete or update the entity in the database using the update and destroy methods in the controller. All articles say that the controller method returns a response in JSON format. Example:
public function index()
{
$users = User::all();
return response()->json($users, 200);
}
public function update(UserRequest $request, $id)
{
$user = User::findOrFail($id);
$user->fill($request->except(['user_id']));
$user->save();
return response()->json($user);
}
public function destroy(UserRequest $request, $id)
{
$user = User::findOrFail($id);
if($user->delete()) return response(null, 204);
}
public function index()
{
$users = User::all();
return view('userlist', compact('users')):
}
public function update(UserRequest $request, $id)
{
$user = User::findOrFail($id);
$user->fill($request->except(['user_id']));
$user->save();
return redirect()->route('userlist');
}
public function destroy(UserRequest $request, $id)
{
$user = User::findOrFail($id);
return redirect()->route('userlist');
}
Answer the question
In order to leave comments, you need to log in
is it necessary to send JSON and server responses 200, 204, 404The REST police won't arrest you, of course. But these are generally accepted conventions. Because...
would this be considered a REST Api...most probably not. Because you will be giving back the data mixed in with the view. And so that, having received a list of entities, the front-end could request detailed information on one of them, it will first need to pick out its identifier from the layout.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question