Axios Request in a Laravel App returns UnexpectedValueException exception

I am using Axios in a Laravel app for a GET request, however for some reason the request is returning the exception: UnexpectedValueException with the message:

"The Response content must be a string or object implementing __toString(), "boolean" given."

The request is returning this exception, regardless of what I include in the response.

Switching out the Axios request for a jQuery request works just fine, so I am assuming it is an issue with the Axios library.

This request returns the exception:

axios.get(`/prospect/fetch`);

However this jQuery request works just fine:

$.get('/prospect/fetch');

Laravel fetch function:

public function fetch() {
    return response()->json([
        'collection' => Prospect::all()
    ]);
}

Route for url:

Route::get('/prospect/fetch', 'ProspectController@fetch')->name('admin.dashboard.prospect.fetch');

What is wrong with the Axios request?

Upvotes: 0

Views: 1298

Answers (2)

Karan Sadana
Karan Sadana

Reputation: 1373

You should read this answer object implementing __toString(), "boolean" given.

Hence, there is some error because of json_encode

you should try toArray() method of collection , which can easily convertable to json.

am always return an array in response than a collection object whenever I have to do some ajax calls or send data to javascript.

$prospect = Prospect::all()->toArray();
    return response()->json([
            'collection' => $prospect,'status'=>200
        ]);

or directly Pass

return response()->json([
                'collection' => Prospect::all()->toArray(),'status'=>200
            ]);

Upvotes: 1

AH.Pooladvand
AH.Pooladvand

Reputation: 2059

As it says the thing that you are returning must be string or an object that is implementing __toString magic method and you gave boolean which is none of those so that is why you are getting that error message.

You can fix the error like this:

public function fetch(Request $request) {
    if($request->ajax()) {
        return response()->json(['is_successful' => true]);
    }
}

Upvotes: 0

Related Questions