I am trying to treat the invalid requests on my Laravel app, something like redirecting to the root will work just fine, but I can't manage to do it.
In the documentation and around stackoverflow I saw this is always the solution:
App::missing(function() {
# handle the error
});
I thought that would just go to the routes file but no. Then I saw in some post it should be in the app/start/global.php file but it still didn't work.
In the docs it says I can "register an error handle". Is that what I should do? What does this mean? What should I do?
Ultimately this can be put anywhere, but app/start/global.php is probably the best place for it.
App::missing(function($exception)
{
return Response::view('errors.missing', array(), 404);
});
Try putting this in there. In fact, if you've just setup a fresh installation, you should already have one there.
Here is how you can register an error handler, like so;
App::error(function(Exception $exception, $code)
{
//Now you can check for different exceptions and handle each on their own way.
}
This will be for PHP general Exception class which will make all exceptions go here, but you can change Exception to the specific Exception class of you own and handle it accordingly.
App::missing will generally be called when a page within your site has not been found, allowing you to show a default page for when users have found a non existing page. So if you are wanting to handle missing pages, use App::missing else use App::error.
Related
I have a working Laravel project with loads of different routes.
I'm currently testing it and one of my tests was to check if a user were to use a delete or post route from the URL. I didn't know what the application would do honestly and it outputted the typical:
The GET method is not supported for this route. Supported methods: DELETE
which I have seen a million times. Is there a way to stop this error from coming up and instead output an error screen or simply redirect to a different view?
The error message:
The GET method is not supported for this route. Supported methods: DELETE.
should only appear when your Laravel site has APP_DEBUG set to true (in the .env file).
When APP_DEBUG is set to false as it should always be in on a live site, then the user will be shown a 404 error page instead.
You can easily test this by adding the following code to your routes file:
Route::delete('test', function() {
return 'You should never see this text when viewing url via a GET request';
});
May be u didn't noticed but ur form tag method attribute and route definition is different
I've been using your advice and View::sharing all of my important data to all views. However, there is one issue I have encountered.
This code:
if(!Auth::guest()){
$user=Auth::user()->id;
}
else $user=0;
$temp=DB::select('query');
View::share('cartnumber', count($temp));
View::share('cartitems', $temp);
doesn't work when put in AppServiceProvider. Or better, it always sets $user=0, even if I am logged in. I thought it is because AppServiceProvider's boot function executes before the site checks if someone is logged in.
I then tried to use a BaseController with a construct function but that doesn't work either. The only solution that seems to work correctly is putting the code in every single Controller for every view! That actually works, which kind of confirms my theory.
But is there anywhere I can put this code without having to copy/paste it in every single Controller? Thanks in advance!
You'd likely want to put this code later in the request life cycle to guarantee an auth user because as others have mentioned middleware/session code has not occured during this part of the framework booting up. You could use a service class to call in all your controllers to avoid the copy pasting. Or If you'd like to achieve this using code in your service provider you could use a View Composer instead of a share this allows you to define a callback/or class that will be called right before the view is returned
view()->composer(['/uri-that-needs-data'], function ($view) {
if (Auth::check()) {
$cart = DB::query(...)->get();
$view->with('cartitems', $cart);
}
});
Check out https://laravel.com/docs/5.7/views#view-composers for more details.
Auth::user() will be empty until the session middleware has run.
The reason you can't access the user inside your service provider is because that code is run during the "bootstrapping" phase of the application lifecycle, when it's doing things like loading filesystem or cache drivers, long before the request is sent through response handlers (including middleware).
Once the application has been bootstrapped and all service providers
have been registered, the Request will be handed off to the router
for dispatching. The router will dispatch the request to a route or
controller, as well as run any route specific middleware.
Source: https://laravel.com/docs/5.7/lifecycle
If you don't want to copy/paste that code everywhere, then one place to put it is in custom route middleware. You can list it after the auth middleware to guarantee a logged-in user.
Edit: View composers are another really good option, as suggested by #surgiie. The reason these can be set up inside a service provider (unlike your example) is because the view composer registers a callback, but doesn't execute it until a much later stage in the application lifecycle.
I am having trouble to create a working redirect in Magento from an observer.Apart from that I need to understand why the exception just like we do in controller does not work in Observer.
The typical exception done in controller is like below (adminhtml controller)
$message = $this->__('Exception Message.');
Mage::getSingleton('adminhtml/session')->addError($message);
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
return;
Somewhere in the blog I read about the below method to redirect from observer.
Mage::getSingleton('core/session')->addError('Exception Message.');
Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getUrl('checkout/cart'));
Mage::app()->getResponse()->sendResponse();
exit;
I don't understand the basic redirection difference when doing with an observer and controller.
Why controller redirection does not work when used in observer.
Please help me out and explain.
Thanks a lot in advance.
See below link and i also have posted code
it might help you.
Source : http://aaronbonner.io/post/418012530/redirects-in-magento-controllers
Redirects in Magento Controllers
In Zend Framework controllers, to output something other than html you will want to disable ViewHelper defaults along with some of the other magic ZF typically weaves.
In Magento, the same thing applies when doing a controller redirect.
I noticed on PHP 5.2 a redirect seemed to be ignored whereas my Macports 5.3 setup it worked. Turns out I was missing a trick, and so a proper redirect in Magento is done as follows:
In MyPackage/MyModule/controllers/MyController.php :
$this->_redirectUrl($this->getUrl('http://www.someurl.com/someresource'));
$this->setFlag('', self::FLAG_NO_DISPATCH, true);
return $this;
Without the setFlag call, your redirect will be ignored. The return call stops any further code execution and sees your redirect get actioned.
I updated to the latest version of Laravel 4 using composer update. Now I'm having a problem with the error handling library it uses - Whoops. When I have an error in my code, for instance an syntax error the following happens:
I reload the page
The actual exception ('Unexpected xxxx at ...') appears for less than a second
Another exception replaces it:
Cannot modify header information - headers already sent by (output started at /Users/planewalker/Sites/jean/welper/vendor/filp/whoops/src/Whoops/Run.php:204)
The code at the above line is this:
// If we're allowed to, send output generated by handlers directly
// to the output, otherwise, return it so that it may be used by
// the caller.
if($this->writeToOutput()) {
echo $output;
}
return $output;
and more specifically the echo $output; part.
Does anyone know why this happens?
UPDATE:
I've now determined that the problem is caused by the set_cookie function in combination with the Whoops library's exception output. It seems that the set_cookie function is called after the Whoops library has started outputting its view.
The only solution I found was to use a different session driver that the 'cookie' one. I've switched to using 'native' and the problem does not appear anymore.
Have you edited the start.php or path.php for echoing debug informations. In the most cases this is the problem.
Because start.php is called before the errorhandler is called and in Laravel for every output headers are sent.
Try updating your Laravel 4:
composer update
This problem should be fixed and you would receive the first exception which is thrown.
When I type an invalid url (non-existent controller), it displays the homepage rather than return a 404 Page Not Found page. Does anyone know the possible reason?
Thanks
Have checked if there is any plugins are registered in the bootstrap and if is it configured to catch the exceptions or set any ACL mechanisms.
Also check the error controller too. may be there is some forwarding methods implemented there.
Hi i've had the same problem and i now know how to fix it:
within the bootstrap have the following init
function _initModules()
{
$this->bootstrap('frontController') ;
$front = $this->getResource('frontController') ;
$front->addModuleDirectory(APPLICATION_PATH . "/modules");
$front->setParam("useDefaultControllerAlways", false);
}
Setting 'useDefault....' will use the default controller when a 404 occurs.
You should also make sure your error controller is setup correctly