1

Say you have a simple resource route like this:

Route::resource('overview', 'OverviewController');

And hit routes which you know don't exist. For example:

/overview/sdflkjdsflkjsd  
/overview/sdflkjdsflkjsd/edit

Which in my case throws Trying to get property of non-object error from my view (as no resource is found)

I looked into adding 'Regular Expression Parameter Constraints' from the docs, but it looks like these are not available for resource routes either (plus don't really fix the problem).

I'm looking for a way to throw a single exception for this kind of thing, which I can then handle once, rather than add logic to each action (or at least the show and edit actions).. if possible.

EDIT After looking around github, I found the exception in the Symphony repo here. Is there a way I can hook into it?

1 Answer 1

3

Since you're getting a Trying to get property of non-object error, I assume you're fetching the resource via YourModel::find();

I'd suggest you use YourModel::findOrFail() instead. Then, you'd be getting a specific type of exception called ModelNotFoundException. Just register an error handler for this.

For instance,

App::error(function(ModelNotFoundException $e)
{
    return Response::make('Not Found', 404);
});

UPDATE: This would actually go into render() method inside the app/Exceptions/Handler.php file in Laravel 5.1, and of course the code would utilize the passed $e parameter instead.

public function render($request, Exception $e)
{
   if ($e instanceof ModelNotFoundException)
   {
        return \Response::make('Not Found', 404);
   }
    return parent::render($request, $e);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, findOrFail is a great answer to this and can be done on one neat line. However it doesn't work in my situation as I am actually querying a relation like this: $overview = $event->overviews->find($id). I'm finding a lot of eloquent model functionality doesn't exist for eloquent collections (another useful one missing is 'whereNotNull').
You can still use it. Just call it on the relationship query instead of the collection. In fact, you could include any where clause you want. So it would be $event->overviews()->whereNotNull('fieldName')->firstOrFail(); Let me explain it in this way. If you call the overviews relationship as a property, it fetches them all as a collection and you get whatever the collection class offers you. However, if you call it as a method, then you're referring to the query builder.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.