4

I have a problem with laravel 4. I want to handle occurred errors like, 404 Not Found or any other errors. But I want to call a controller when such errors occurs. I've tried this:

App::missing(function($exception)
{
    return Response::view('errors.404', array('error'=>$exception), 404);
});

But actually above code is not my purpose, I want something like this:

//I know this code doesn't work, I've just wanted to show the claim
App::missing('HomeController@error');
App::error('HomeController@error');
// or ...

Is there any way to handle errors within calling a specific controller's method?

2 Answers 2

5

Nothing's going to stop you from creating an instance of your controller and calling the method you want to call.

App::missing(function($exception)
{
    return App::make('HomeController')->error($exception);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Pass the $exception, like return App::make('HomeController')->error($exception);.
I'm using this approach but if the request doesn't match any route, I get a 'Call to a member function filter() on a non-object' error (details here). But If the request matches a route but no model is found (e.g. firstOrFail()) it works normally. Any idea?
3

No, you can't use App::missing('Controller@method') directly because the missing method calls error method and that is:

public function error(Closure $callback)
{
    $this['exception']->error($callback);
}

It accepts a closure but you may call a controller->method from the closure. So. declare the handler using a closure as usual and then call a controller's method from within the closure.

As a side note, I don't see any importance to call a method from a controller through/within the closure because you may do the same thing (most probably you'll return a view) from the closure then why just another layer ?

Update:

App::missing(function($e){
    // Use the model here you want
    $var = 'SomeValue' from model
    return Response::view('errors.404', array('error'=> $e, 'another' => $var));
});

8 Comments

Actually I'm trying to pass some variables form model to that view. Do you have any suggestion or better solution to do this ?
You mean I directly write the model inside the router.php and don't pass it to controller ?
Check this article for handling menu/nav bar smartly.
I'm using the update code which is working fine. But I'll read the article indeed. Thanks.
You may also check laravel-repository-pattern.
|

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.