In this post, I will discuss how to choose one from the other between redirection and returning views.
I come across a confusion that when a user click a button, should I use redirection or returning views.
After researching, I figure out the difference between the two.
Return a view in a controller when you are responding to a URL. It does not change the URL, but just show users a new view.
A redirect is actually changing the URL which means you actually invoke another controller’s method.
- For example, when someone tries to login by accessing the page /login and the authentication fails, you want to redirect him back to the login page (note that submitting the login form will result in a post request and you don’t want to return view from a post request as it only meant to process data).
- Another example is when a user tries to access a uri such as /profile and he’s not authenticated, you can’t show him the profile, you want to show him the login form, but if you return the login form view, your uri will be /profile and you will display the login form, doesn’t make sense and it will complicate your code so much. What you do in this example just redirect the user to the login page which results in a page refresh and actually hitting another route.