Laravel 5: Handle exceptions when request wants JSON

前端 未结 8 1724
野的像风
野的像风 2021-01-30 05:30

I\'m doing file uploads via AJAX on Laravel 5. I\'ve got pretty much everything working except one thing.

When I try to upload a file that is too big (Bigger than

8条回答
  •  我在风中等你
    2021-01-30 05:44

    In your application you should have app/Http/Middleware/VerifyCsrfToken.php. In that file you can handle how the middleware runs. So you could check if the request is ajax and handle that how you like.

    Alternativly, and probably a better solution, would be to edit the exception handler to return json. See app/exceptions/Handler.php, something like the below would be a starting place

    public function render($request, Exception $e)
    {
        if ($request->ajax() || $request->wantsJson())
        {
            $json = [
                'success' => false,
                'error' => [
                    'code' => $e->getCode(),
                    'message' => $e->getMessage(),
                ],
            ];
    
            return response()->json($json, 400);
        }
    
        return parent::render($request, $e);
    }
    

提交回复
热议问题