Laravel 路由模型绑定:找不到模型 id 时返回 json 响应

wiw*_*978 4 laravel

我正在 Laravel 中开发 REST API。我正在使用路由模型绑定来更新项目。当在数据库中找不到 id 时,我想返回 JSON 未找到响应。

这是路由文件中的条目api.php:

   Route::get('product/{product}', 'ProductController@show')->name('products.show');
Run Code Online (Sandbox Code Playgroud)

控制器更新函数如下所示:

   public function update(Request $request, Product $product)
    {
        $request->validate([
            'user_id'       =>  'required',
            'name'          =>  'nullable',
            'description'   =>  'nullable',
            'price'         =>  'nullable'
        ]);

        // check if currently authenticated user is the owner of the listing

        if (auth::user()->id !== $product->user_id) {
            return response()->json(['error' => 'You can only edit your own products.'], 403);
        }

        $product->update($request->only(['name', 'description', 'price']));

        return new ProductResource($product);
    }
Run Code Online (Sandbox Code Playgroud)

使用此代码,Laravel 自动返回一个404 Not found视图,但我希望它是一个 JSON 响应。

有什么优雅的解决方案可以实现这一点吗?

dpa*_*oli 8

您可以尝试app/Exceptions/Handler.php使用类似的内容修改文件:

// add this before the class declaration
use Illuminate\Database\Eloquent\ModelNotFoundException;
//....
// modify the render() function as follows
public function render($request, Exception $exception)
{
    if ($exception instanceof ModelNotFoundException && $request->wantsJson()) {
        return response()->json(['message' => 'Not Found'], 404);
    }
    return parent::render($request, $exception);
}
Run Code Online (Sandbox Code Playgroud)

让我知道它是否有效我没有时间尝试代码。