D
D
Dmitry Kuznetsov2019-01-31 14:52:34
API
Dmitry Kuznetsov, 2019-01-31 14:52:34

Why does the Laravel API respond with a 404 error under some circumstances?

Hello. I am creating my own API for one service. For testing I use Insomnia Rest.
It happens that the response to the API, the user, should receive an error code, but instead a 404 error is issued.
For example, if the user is not found:
UserController :

<?php
namespace App\Http\Controllers\Users;

use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UsersController extends Controller{

    public function show($id){
        return User::findOrFail($id);
    }
}

API :
Route::group(['middleware' => 'auth:api'], function(){
    Route::resource('users', 'Users\UsersController');
});

But for some reason a 404 error is displayed. If the user is found, it is displayed as it should. Please tell me how to correctly issue such errors in JSON format ?! Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikolai Komyagin, 2021-02-26
@no_brain_nopain

https://laravel.demiart.ru/laravel-api-404-answer-v...
the answer is briefly and clearly described here
I did it like this

public function render($request, $e)
    {
        if ($e instanceof ModelNotFoundException) {
            return response()->json([
                'success' => false,
                'errors' => ['Record not found'],
                'data' => [],
            ], 404);
        }
        return;
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question