Frederik
Frederik

Reputation: 667

Laravel - prevent access to controller throug route in url

I'm working on a website based on Laravel. In my forms, I use routing to tell the form where to post my data, for instance route('login'), which could point to http://localhost:3000/login. However, if I manually write http://localhost:3000/login in the browser, I get a MethodNotAllowedHttpException which is fine, but how do I prevent the end user from seeing this exception and instead just returning him to the index page?

Upvotes: 2

Views: 2159

Answers (3)

Jesus Erwin Suarez
Jesus Erwin Suarez

Reputation: 1585

It's bad practice to redirect if that's the issue, you may take a look with this solution:

go to your .env file and add this code


  APP_ENV=production
  APP_DEBUG=false

and in


   resources/views/errors/405.blade.php

This will handle the error for MethodNotAllowedHttpException so of course you can customize the ui and message in that file.

Hope that helps!

Upvotes: 0

Jorge Herrera
Jorge Herrera

Reputation: 25

Laravel has a lot of features to make authentication easier, if you want to implement a login, this is what I do in all my developments, inside your project folder in the cmd just type:

  • Run php artisan make:auth - This creates some controllers and views to manage authentication
  • Run php artisan migrate - This creates the necessary tables in database

and now, you can refresh the site, and the authentication is done, you can get more information here https://laravel.com/docs/5.6/authentication,

if this is not what you want, I think the most reccomended for your case, could be a middleware, a middleware intercepts every request before to resolve it, so there you can make any validation that you want for every request, again, to get more information about it, here https://laravel.com/docs/5.6/middleware#terminable-middleware

Upvotes: 0

ashraj98
ashraj98

Reputation: 384

You get a MethodNotAllowedHttpException because your login route probably requires a POST request to get to the login view, and typing the URL directly is a GET request. You can redirect all GET requests to /login by adding this to routes/web.php:

Route::get('/login', function () {
    return redirect('/');
});

and you can replace '/' with whatever URL points to your index page.

Upvotes: 2

Related Questions