Redirect wrong url laravel 5.1 - laravel

Route :
Route::get('/', function () {
return view('login');
});
and then try to visit this link:
http://www.example.com/wrongurl
How to redirect to specific page if someone trying to access wrong url thats not listed on router ?

You can use the Handler. In the app/Exceptions/Handler.php file you have to add two lines of code in the render functions:
public function render($request, Exception $e)
{
if ($e instanceof ModelNotFoundException) {
$e = new NotFoundHttpException($e->getMessage(), $e);
}
if($e->getStatusCode() == '404') {
return redirect('/');
}
return parent::render($request, $e);
}

You can add as last route this:
Route::get('/{any}', function($any){
redirect('/')'
})->where('any', '.*');
This will redirect any missing get route to /.

If you have learned to use controllers. This will help.
Route::get('/home',Pagecontroller#homepage);
Route::get('/aboutus',Pagecontroller#aboutus);
Route::get('/contactus',Pagecontroller#contactus);
.
.
.
/*last route should be for the unknown url*/
Route::get('/{any}',Pagecontroller#indexpage); //this will redirect to the index page if any unknown routing url is given by mistake or by purpose.
'/{any}' will read all other url which is not declared.
make sure that you use it at the end, after declaration of all other valid routes

you can add the following code in Exception Handler file i.e. app\Exceptions\Handler.php
public function render($request, Exception $exception)
{
if($this->isHttpException($exception)){
if ($exception->getStatusCode()=='404') {
return redirect('/');
}else{
return parent::render($request, $exception);
}
}else{
return parent::render($request, $exception);
}
}

Related

laravel MethodNotAllowedHttpException redirect to 404

I use laravel 8 tried to edit my exceptions\handler.php
public function render($request, Throwable $exception)
{
if ($exception instanceof MethodNotAllowedHttpException) {
abort(404);
}
return parent::render($request, $exception);
}
but his gives not 404 but 500 when checking routes where MethodNotAllowedHttpException
One possible solution is to supply your routes/web.php file with a Route fallback. Try adding the following to the bottom of your web routes:
Route::fallback( function () {
abort( 404 );
} );
on Laravel 8 override default handler render function on App\Exceptions\Handler.php
public function render($request, Throwable $exception)
{
if ($exception instanceof MethodNotAllowedHttpException) {
if ($request->ajax() || $request->wantsJson() || $request->expectsJson()) {
//405 for Method Not Allowed
return response()->json(['error' => 'Bad Request'], 405);
}
else {
return parent::render($request, $exception);
}
}
}
don't forget to add use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;to test in Postman set key=>Accept ,value => application/json to test handler
reff: Return a 404 when wrong ttp request type used(e.g. get instead of post) in laravel

Only load route with existent parametre

Im doing a crud, i want to show item data using id, i have this in web.php:
Route::get('update/{id}', 'CrudController#update');
How can I deny that the user changes the id in the path to one that does not exist? That shows only those that exist and those that do not, that do not load?
In your update method, you can do the following:
public function update($id)
{
MyModel::findOrFail($id);
//...perform other actions
}
It will throw a 404 response if the requested $id is a non-existent one.
Then you can catch it if you want in the render() method of app\Exceptions\Handler.php:
use Illuminate\Database\Eloquent\ModelNotFoundException;
.
.
.
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException) {
if ($request->wantsJson()) {
return response()->json([
'data' => 'Resource not found'
], 404);
} else {
abort(404);
}
}
return parent::render($request, $exception);
}
Or, If you do not want to go through all the trouble of configuring it in the handler, you could also do:
public function update($id)
{
if (! $model = MyModel::find($id)) {
abort(404);
}
//...perform other actions with $model
}
The abort(404) method takes the user to the default Page not found page of laravel, which is an appropriate thing to do.

Having a controller on 404 urls using Laravel 5

I need to have a custom controller triggered when user hits a not-existing url or when I programmatically force an App::abort(404).
How can I do it?
My 404 views need some data, and a simple blade View (or a ViewComposer) is not enough.
Thanks
PS catch-all urls is not functional, because they don't catch programmatically launched 404.
Edit the render function of App\Exceptions\Handler class and add something about 404 here:
if ($this->isHttpException($exception) && $this->getStatusCode() == 404) {
// Do what you want...
// You can even use the $request variable
}
Full example:
public function render($request, Exception $exception)
{
if ($this->isHttpException($exception) && $this->getStatusCode() == 404) {
echo 'hello from 404 renderer';
dd($request); // Or you can a view.
}
return parent::render($request, $exception);
}
Try to return a redirect() to your custom Controller instead of a response() from the Handler's render() method if the exception is 404. You can retrieve the the page requested from the $request then right ?
Here is the sample:
public function render($request, Exception $exception)
{
if ($this->isHttpException($exception) && $this->getStatusCode() == 404) {
return redirect(route('route.to.custom.controller'))->with('request', $request);
}
return parent::render($request, $exception);
}
Hope that will help, cheers !

Redirect to homepage if route doesnt exist in Laravel 5

/** Redirect 404's to home
*****************************************/
App::missing(function($exception)
{
// return Response::view('errors.missing', array(), 404);
return Redirect::to('/');
});
I have this code in my routes.php file. I am wondering how to redirect back to the home page if there is a 404 error. Is this possible?
For that, you need to do add few lines of code to render method in app/Exceptions/Handler.php file which looks like this:
public function render($request, Exception $e)
{
if($this->isHttpException($e))
{
switch ($e->getStatusCode())
{
// not found
case 404:
return redirect()->guest('home');
break;
// internal error
case '500':
return redirect()->guest('home');
break;
default:
return $this->renderHttpException($e);
break;
}
}
else
{
return parent::render($request, $e);
}
}
I just want to add a suggestion for cleaning it up a bit more. I'd like to credit the accepted answer for getting me started. In my opinion however since every action in this function will return something, the switch and else statement create a bit of bloat. So to clean it up just a tad, I'd do the following.
public function render($request, Exception $e)
{
if ($this->isHttpException($e))
{
if ($e->getStatusCode() == 404)
return redirect()->guest('home');
if ($e->getStatusCode() == 500)
return redirect()->guest('home');
}
return parent::render($request, $e);
}
you may Just do this :
open : app\Exceptions\Handler.php
in handler.php you can replace this code :
return parent::render($request, $exception);
by this : return redirect('/');
it works good
,example :
public function render($request, Exception $exception)
{
return redirect('/');
//return parent::render($request, $exception);
}

Laravel 5 Error Handling

I am using Laravel 5 and I am trying to make custom 404 page and custom Exception handling, but I can't figure out where to put my code. Some time ago there was an ErrorServiceProvider that no longer exists. Can anyone give me some pointers?
EDIT: I saw they have added a Handler class in the App/Exception folder but that still seems not the right place to put it because it does not follow at all the laravel 4.2 App::error, App::missing and App::fatal methods. Anyone has any ideas?
Use app/Exceptions/Handler.php render method to achieve that. L5 documentation http://laravel.com/docs/5.0/errors#handling-errors
public function render($request, Exception $e)
{
if ($e instanceof Error) {
if ($request->ajax()) {
return response(['error' => $e->getMessage()], 400);
} else {
return $e->getMessage();
}
}
if ($this->isHttpException($e)) {
return $this->renderHttpException($e);
} else {
return parent::render($request, $e);
}
}
Here is how to customize your error page while complying with the APP_DEBUG setting in .env.
app/Exceptions/Handler.php
public function render($request, Exception $e)
{
if ($this->isHttpException($e))
{
return $this->renderHttpException($e);
}
else
{
if (env('APP_DEBUG'))
{
return parent::render($request, $e);
}
return response()->view('errors.500', [], 500);
}
}

Resources