user3732216
user3732216

Reputation: 1589

Laravel ApiException returning HTML response and not JSON

I'm trying to figure out why my ApiException is still returning a text/html response instead of a json response as denoted in ApiException render method. It is giving me the correct error message however its not rendering it as json.

/**
 * Get the checklist (depending on type - send from Vue model)
 */
public function fetchChecklist(Request $request)
{
    $id = $request->input('projectId');
    $type = $request->input('type');

    if (empty($id)) {
        throw new ApiException('Project was not provided.');
    }

    if (! $project = RoofingProject::find($id)) {
        throw new ApiException('Project not found.');
    }

    if (empty($type)) {
        throw new ApiException('No checklist type was provided.');
    }

    switch ($request->input('type')) {
        case 'permitting':
            $items = $project->permittingChecklist;
            break;

        case 'permit':
            $items = $project->permitReqChecklist;
            break;

        default:
            throw new ApiException('Checklist not found.');
            break;
    }

    return [
        'status' => 'success',
        'message' => '',
        'items' => $items
    ];
}

App\Exceptions\ApiException.php

<?php

namespace App\Exceptions;

class ApiException extends \Exception
{
    public function render($request)
    {
        return response()->json(['status' => 'error', 'error' => $this->message]);
    }
}

Upvotes: 4

Views: 6594

Answers (2)

Mahmoud Youssef
Mahmoud Youssef

Reputation: 808

It worked for me with setting the following header as so

"x-requested-with": "XMLHttpRequest"

Upvotes: 3

jeremykenedy
jeremykenedy

Reputation: 4275

In your request to the API you can try to add the following to your head/curl call to specify the datatype:

"Accept: application/json"

The laravel application is looking for if the requests expects json.

Upvotes: 9

Related Questions