I
I
Ilya Loopashko2021-07-09 09:24:16
Laravel
Ilya Loopashko, 2021-07-09 09:24:16

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,
    ]);
}


In each method, I return the same array. I want to change the code to something like this. But I can not yet figure out where to start, tell me how this can be done.

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;
}


I looked at the option to create a Resource or Repositories. But it's not what I need.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya Loopashko, 2021-07-09
@deadloop

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 не обнаружена');
    }

ResponseRepository.php
public static function Response($message = "Ошибка", $data = null, $status = false)
    {
        return response()->json([
            'status' => $status,
            'message' => $message,
            'data' => $data,
        ]);
    }

P
pLavrenov, 2021-07-09
@pLavrenov

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 question

Ask a Question

731 491 924 answers to any question