2
votes

I'm creating an API to access my blog entries, and rather than Laravel model binding returning a 404 automatically, I'd rather return a 200, and some JSON in the same format as my API controller returns.

I use the code below, which when returning the JSON response works within controllers, but I can't get it working within a Route::bind, instead the JSON output is as follows:

{"success":true,"data":{"headers":{}}}

Here is my code within app/global.php

Route::group(array('prefix' => '/api/blog'),function() {
    Route::bind('blog', function($id) {
        $Blog = Blog::find($id);
        if (!$Blog) {
            return Response::json(array('status' => false, 'message' => 'Blog not found'), 200);
        }
    });

    Route::get('index', array('uses' => 'BlogController@index'));
    Route::get('create', array('uses' => 'BlogController@create'));
    Route::get('read/{blog}', array('uses' => 'BlogController@read'));
});

It even does this if I try and return an empty array in the JSON response like so:

return Response::json(array(), 200);
2
I screwed up the formatting of my Route::group but it's all theresynkyo

2 Answers

1
votes

After a little more thought, I realised I could define a new exception to throw, and then simply catch that exception type.

Route::group(array('prefix' => '/api/blog'),function() {
    Route::bind('blog', function($id) {
        $Blog = Blog::find($id);
        if (!$Blog) {
            throw new ApiException('Blog not found');
        }
    });
    Route::get('index', array('uses' => 'BlogController@index'));
    Route::get('create', array('uses' => 'BlogController@create'));
    Route::get('read/{blog}', array('uses' => 'BlogController@read'));
});
class ApiException extends Exception {}
App::error(function(ApiException $ex) {
    return Response::json(array('status' => false, 'message' => $ex->getMessage()));
});
0
votes

If you really want to use the nonstandard REST API then you need to implement the API methods yourself instead of using Route::bind.

Get the input parameters in your controller method, resolve the Eloquent manually and then send a response that you want to.