How to redirect to another view in Laravel

Issue

I’m using Laravel 5.2. I have a simple form on the homepage. When a user clicks search on that form it should send them to a registration page. It’s just a dummy form so no data is being submitted. I’m not sure what I need to put in my routes file. Do I need to put something in my controllers file as well? Any help will be appreciated.

This is what I have on my main page…

form action="{{route('register')}}" method="post"

Solution

So you want to go to the “register” page when the form is submitted. Why would you want to do that? Though if you want to do that, @Vinicius answer is correct. I think what you want is – “If my users are logged in, then do the search, instead go to the register page”.

To do what I am proposing, you will have to categorize your routes in middleware.

So in your routes file, you will define this route.

Route::post('search', ['middleware' => 'auth', function () {
    return view('search');
}]);

This route will make sure that the “search functionality” method is only accessible when you are logged in. If laravel finds that the user is not logged in, it will automatically redirect the user to the register page.

For more information look at this code. This is the middleware functionality which decides if the user is logged in or not. As you can see, laravel by default will redirect the user to the login page. For you to redirect user to the register page, change the line to this.

return redirect()->guest('register');

Answered By – Rash

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published