2

I'm creating an API with Laravel based on the Dingo API.

In my routes, I have:

Route::api('v1', function () {
    Route::resource('object', 'My\Namespace\MyController');
});

And in MyController:

class MyController extends \Illuminate\Routing\Controller {

    use Dingo\Api\Routing\ControllerTrait;

    public function index() {
        return MyObject::all();
    }

    public function show($id) {
        return MyObject::findOrFail($id);
    }

}

This means that api.domain.com/object calls MyController@index, which works. Since there are no items in the database, this then outputs an empty json array [].

api.domain.com/object/123 calls MyController@show(123). This is according to https://github.com/dingo/api/wiki/Responses. However, since there are no results in the database, I get:

No query results for model [My\Namespace\MyObject].

I would expect this to give a nice RESTful error instead. How do I do that?

The code of MyObject is nothing special, it's an empty class which extends Illuminate\Database\Eloquent\Model.

I'm using Laravel 4.2; 5 is not supported by Dingo yet.

1 Answers1

3

You'll have to handle it yourself and add a custom error as described here. findOrFail() will throw a ModelNotFoundException so let's catch that:

API::error(function (Illuminate\Database\Eloquent\ModelNotFoundException $e){
    return Response::make(['error' => 'Resource not found'], 404);
});
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • That makes sense, thanks. So where would be the best place to put that code? This is in my own package - should I put it in the ServiceProvider? –  Feb 21 '15 at 11:43
  • Yes inside a ServiceProvider is the perfect place for that :) – lukasgeiter Feb 21 '15 at 11:44
  • @CamilStaps Exactly :) – lukasgeiter Feb 21 '15 at 11:49
  • I'm sorry, I was a little hasty with accepting because I still have a small problem. Now, I'm getting `Call to undefined method Dingo\Api\Http\Response::make()`. What Response class are you using here exactly? Also the `Symfony\Component\HttpFoundation\Response` class doesn't work (same error). –  Feb 21 '15 at 11:58
  • 1
    That's just Laravels `Response` facade. (`Illuminate\Support\Facades\Response`). But there is an alias in the global namespace so you shouldn't even need to import it... – lukasgeiter Feb 21 '15 at 12:01
  • That works, thanks very much! (Without anything, I got `Class 'My\Namespace\Response'` not found.) –  Feb 21 '15 at 12:03
  • 1
    Ah I see... you also just do `\Response::make()` or `use Response;` at the top. Or as you now probably did `use Illuminate\Support\Facades\Response` – lukasgeiter Feb 21 '15 at 12:08