简体   繁体   中英

Can't get a simple Laravel Login controller setup to work

I am just starting with Laravel after finally deciding to move from CodeIgniter, however I cannot get a simple login form to work. I keep getting that "MethodNotAllowedHttpException" error.

Here is how my Controller looks

class LoginController extends BaseController {

    public function login()
    {
        $username = $_POST['username'];
        $password = $_POST['password'];
        Login::login($username, $password); 
        // ^ Call to Login model to check the user's credentials - everything fine there
    }

}

Here is my view

{{ Form::open(array('url' => 'LoginController/login')) }}
        {{ Form::text('username') }}
        {{ Form::password('password') }}
        {{ Form::submit('Submit') }}
{{ Form::close }}

And my route for this is like

Route::get('LoginController/login', 'LoginController@login');

I'm doing something horribly wrong somewhere, can you guys please point it out?

Thanks!

Seems like you are just routing the GET method. You should also route the POST method to make your controller work:

Route::get('LoginController/login', 'LoginController@login');
Route::post('LoginController/login', 'LoginController@login');

Normally, It is better to have to separate methods in your controller to handle different logic. Something as follow:

Route::get('login', 'LoginController@showLogin');
Route::post('login', 'LoginController@processLogin');

That way you will have your controller's methods more specific, one that just show the login page, and the other that actually do the login process.


Update

If you want to retrieve input values within Laravel, you should use the Input class, so you will replace your current code:

$username = $_POST['username'];
$password = $_POST['password'];

to be as follow:

$username = Input::get('username');
$password = Input::get('password');

Happy coding!

You need to specify a form method as POST so that it reads

{{ Form::open(array('url' => 'LoginController/login', 'method'=>'POST')) }}
        {{ Form::text('username') }}
        {{ Form::password('password') }}
        {{ Form::submit('Submit') }}
{{ Form::close }}

And the in your routes file add the following

Route::post('/login', array('uses' => 'LoginController@login')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM