Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel throwing MethodNotAllowedHttpException

I am trying to get something very basic running. I am used to CI and now learning Laravel 4, and their docs are not making it easy! Anyways, I am trying to create a login form and just make sure that data is posted successfully by printing it in the next form. I am getting this exception:

Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException

and my MemberController.php:

    public function index()     {         if (Session::has('userToken'))         {             /*Retrieve data of user from DB using token & Load view*/             return View::make('members/profile');         }else{             return View::make('members/login');         }     }      public function validateCredentials()     {         if(Input::post())         {             $email = Input::post('email');             $password = Input::post('password');             return "Email: " . $email . " and Password: " . $password;         }else{             return View::make('members/login');         }     } 

and routes has:

Route::get('/', function() {     return View::make('hello'); });  Route::get('/members', 'MemberController@index'); Route::get('/validate', 'MemberController@validateCredentials'); 

and finally my view login.php has this form direction:

<?php echo Form::open(array('action' => 'MemberController@validateCredentials')); ?> 

Any help will be greatly appreciated.

like image 673
spacemonkey Avatar asked Nov 04 '13 02:11

spacemonkey


2 Answers

You are getting that error because you are posting to a GET route.

I would split your routing for validate into a separate GET and POST routes.

New Routes:

Route::post('validate', 'MemberController@validateCredentials');  Route::get('validate', function () {     return View::make('members/login'); }); 

Then your controller method could just be

public function validateCredentials() {     $email = Input::post('email');     $password = Input::post('password');     return "Email: " . $email . " and Password: " . $password; } 
like image 120
hayhorse Avatar answered Sep 28 '22 07:09

hayhorse


My suspicion is the problem lies in your route definition.

You defined the route as a GET request but the form is probably sending a POST request. Change your route definition to match the form's request method.

Route::post('/validate', [MemberController::class, 'validateCredentials']); 

It's generally better practice to use named routes (helps to scale if the controller method/class changes).

Route::post('/validate', [MemberController::class, 'validateCredentials'])     ->name('member.validateCredentials'); 

In the view, use the validation route as the form's action.

<form action="{{ route('member.validateCredentials') }}" method="POST">   @csrf ... </form> 
like image 21
Blessing Avatar answered Sep 28 '22 09:09

Blessing