I am trying login authentication but showing an error message. Hope an expert helps me to get the solution.
This is my HTML code:
<form action="{{url('/')}}/login" method="post">
@csrf
<div class="fields">
<div class="input-field">
<label for="un" >UserName</label>
<div class="inpt">
<input type="text" id="un" placeholder="Enter UserName" required></div>
</dev>
</div>
<div class="input-field">
<label for="pw">Password</label>
<div class="inpt">
<input type="password" id="pw" placeholder="Enter Your password" required>
</div>
</div>
<div>
<input type="checkbox" id="rm" >
<label for="rm">Remember Me</label>
</div>
<div class="input-field-1">
<button type="submit">Login</button>
</div>
</div>
</form>
This is my controller:
public function login():View
{
return view('login');
}
public function authenticate(Request $request)
{
$credentials = $request->validate([
'email' => 'required|email',
'password' => 'required'
]);
if(Auth::attempt($credentials))
{
$request->session()->regenerate();
return redirect()->route('index')
->withSuccess('You have successfully logged in!');
}
return back()->withErrors([
'email' => 'Your provided credentials do not match our records.',
])->onlyInput('email');
}
This is my route(web.php):
Route::get('/login',[Registrationcontroller::class,'login'])->name('login');
Route::post('/authenticate', [Registrationcontroller::class, 'authenticate'])->name('authenticate');
Error:
The POST method is not supported for route login. Supported methods: GET, HEAD.
3
Answers
You should adjust your form’s "action" attribute to submit the form to your "authenticate" route:
Using the
route
method gives us an absolute URL to a named route.Beware: your
/login
route accepts GET method only, as you can see in your web.php. And that is good because in you login route and controller function u use it for show the view with the login form.You should make a POST request to
/authenticate
route where your credentials would be validated and, if correct it would redirect you to the index with an authenticated session, otherwise would send you back to the login view.You should also use the
{{ route('authenticate') }}
function in your form action to make laravel generate the URL the right way.That being said you should also show the errors on your form, so if there is something going wrong with authentication you would know!
Hope this helps
Your form action should be pointed to the
/authenticate
endpoint, also you can use named route{{ route('authenticate') }}
Your HTML form code should be
OR:
When you use a named route you should be careful if you have any prefix name