Answer the question
In order to leave comments, you need to log in
Customize and optimize the response (Response)?
Vmem hello. I have a CRUD API controller that returns a result after successful execution.
Example method, removal
public function destroy(Request $request)
{
$idle = Idle::find($request->get('id'));
if ($idle !== null) {
[$status = "OK", $message = "Запись с таким id удалена"];
$idle->delete();
} else {
[$status = "Error", $message = "Запись с таким id не обнаружена"];
}
return response()->json([
"status" => $status,
"message" => $message,
"data" => $idle,
]);
}
public function destroy(Request $request, Response $response)
{
$idle = Idle::find($request->get('id'));
$response->data['idle'] = $idle;
if ($idle !== null) {
$response->status = 'OK';
$response->message = "Запись с таким id удалена";
$idle->delete();
} else {
$response->message = "Запись с таким id не обнаружена";
}
return $response;
}
Answer the question
In order to leave comments, you need to log in
Thanks to everyone for the answers, I did a little digging and implemented it through the Repositories.
public function destroy(Request $request)
{
$idle = Idle::find($request->get('id'));
if ($idle !== null) {
$idle->delete();
return $this->responseRepository->Response($idle, true, 'Запись с таким id удалена');
}
return $this->responseRepository->Response('Запись с таким id не обнаружена');
}
public static function Response($message = "Ошибка", $data = null, $status = false)
{
return response()->json([
'status' => $status,
'message' => $message,
'data' => $data,
]);
}
1) Response name capitalized?
2) Response is static?! Oo
3) Why is it needed in the repository?
4) Learn Dependency Injection in Laravel
5) Learn REST and Routing
6) Learn Validation in Laravel
Read the documentation from beginning to end (it's not long), so you will understand what is there and where you can look.
After the points above, the code will look something like this
public function destroy(Request $request, Idle $idle)
{
// Оставил ее тут но ее надо бы вынести отдельно
$request->validate([
'some' => 'required',
]);
return response()->json([
'success' => $idle->delete(),
]);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question