Search code examples
jqueryajaxlaravelgetaxios

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?


Solution

  • 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
                ]);