Laravel 5 : Method Not Allowed Http Exception in R

2019-02-27 12:57发布

问题:

I have a sign-up form and getting the sign-up form values in routes.php. My rout.php code is :

Route::get('/', function () {

    return view('login');
});

Route::get('/index', function(){
    return view('index');
});

Route::get('/register', function(){
    return view('register');
});

Route::post('/register',function(){
    $user = new \App\User;
    $user->username = input::get('username');
    $user->email  = input::get('email');
    $user->password = Hash::make(input::get('username'));
    $user->designation = input::get('designation');
    $user->save();

});

The form action is to index.php and also have hidden field for csrf_token():

<form action="index" method="post">         
<input type="hidden" name="_token" value="{{ csrf_token() }}">

The error is : Method Not Allowed Http Exception in Route Collection.php line 201:

回答1:

You have correctly registered a route with the post method on the page /register, but in the form you do a post to the index route. Change

   <form action="index" method="post">         
   <input type="hidden" name="_token" value="{{ csrf_token() }}">

to

   <form action="register" method="post">         
   <input type="hidden" name="_token" value="{{ csrf_token() }}">

to send the post values to the register route instead of the index route. You don't return a view or redirect at the end of your register function so I would either add return view('index'); or return redirect('index'); as last line of your register function to redirect the user to the index page (or just return the index view)

Alternatively you can change the index route to accept post values:

Route::post('/index', function(){
    return view('index');
});