peterxz
peterxz

Reputation: 874

Laravel API overriding default 413 Payload Too Large response

I am creating file uploader in my Laravel API, but seems like when I upload a file that is too large, the response is muddled up and I can't really figure out how to solve. Here is a screenshot of my postman request: enter image description here

As you can see if have application/json header, and what is bugging me is the PHP error before the empty json response. What I want instead is for the warning message not to appear and the response to be customised.

I tried adding the exception to my Handler.php as follows, but made not much difference (although I am not 100% sure this is the correct exception to intercept as its not being logged):

public function register() {
    $this->renderable(function (Throwable $e, Request $request) {
        //
        switch($e) {
            case $e instanceof \PostTooLargeException:
                response()->json(['message' => "The size of the selected file is too large.", "success" => false], 413);
                break;
            default:
                response()->json(['message' => 'Server error.', 'success' => false], 500);

        }

    });
}

Controller function I am posting to:

public function uploadTo(Request $request, $album_id) {
    if(!$request->hasFile('image')) {
        return response()->json(['message' => 'File not found', 'success' => false], 400);
    }

    $file = $request->file('image');
    if(!$file->isValid()) {
        return response()->json(['message' => "Invalid file upload.", "success" => false], 400);
    }

    $album = Album::where('id', $album_id)->first();
    //\Storage::disk('frontend')->allFiles($this->folder_name);

    $file->store("$album->folder_name", ["disk"=>"frontend"]);
    //$file->move($path, $file->getClientOriginalName());

    return response()->json(['message'=>"Upload successful.", "success" => true], 200);
}

What am i doing wrong here? Just to be clear I do not want to increase the upload size / php size limit, I just want to intercept the error message and return a graceful error.

Upvotes: 0

Views: 3660

Answers (2)

peterxz
peterxz

Reputation: 874

The solution:

After all I had to mess around with my php.ini settings, but only setting display_startup_errors = Off gets rid of the annoying warning, then changing \PostTooLargeException in my Handler.php to \Illuminate\Http\Exceptions\PostTooLargeException properly catches the exception and overrides the error.

Upvotes: 0

Othmane Nemli
Othmane Nemli

Reputation: 1193

Try to update your php.ini (you can put any size you like)

max_file_uploads=100
post_max_size=120M
upload_max_filesize=120M

If you are using homestead try also to update nginx (

/etc/nginx/nginx.conf

http {
      client_max_body_size 50M;         
}

restart after that

sudo service nginx restart

Upvotes: 1

Related Questions