Reputation: 1099
In my application I get the id from the route/URL. What should I do in my controller if there is no object with this id?
My favorite solution would be to throw a 404. Is this a good idea? Are there any helpers for this common problem?
// url /groups/1
public function group($group_id)
{
if (! Group::find($group_id)) {
App::abort(404);
}
}
In Django there is a short cut function for this problem. https://docs.djangoproject.com/en/1.6/topics/http/shortcuts/#get-object-or-404
Upvotes: 1
Views: 471
Reputation: 20486
Eloquent::findOrFail($pk)
is what you are looking for. This will throw a ModelNotFoundException
. Here's how I would set this up:
Controller
public function group($group_id)
{
// This will throw an App::error() when $group_id doesn't exist
$group = Group::findOrFail($group_id);
}
Routes (or something similar)
App::error(function(Illuminate\Database\Eloquent\ModelNotFoundException $e)
{
// This will be ran when ::findOrFail() doesn't find an object
App::abort(404);
});
Upvotes: 3