Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 - two submit buttons in one form and have both submits to be handled by different actions

Tags:

I have a login form which has email and password fields. And I have two submit buttons, one for login ( if user is already registered ) and the other one for registration ( for new users ). As the login action and register action are different so I need some way to redirect the request with all the post data to its respective action. Is there a way to achieve this in Laravel 4 in pure Laravel way?

like image 576
Abhay PS Avatar asked Jan 05 '14 10:01

Abhay PS


2 Answers

The way I would do it

If your form is (2 buttons):

{{ Form::open(array('url' => 'test/auth')) }} {{ Form::email('email') }} {{ Form::password('password') }} {{ Form::password('confirm_password') }} <input type="submit" name="login" value="Login"> <input type="submit" name="register" value="Register"> {{ Form::close() }} 

Create a controller 'TestController'

Add a route

Route::post('test/auth', array('uses' => 'TestController@postAuth')); 

In TestController you'd have one method that checks which submit was clicked on and two other methods for login and register

<?php  class TestController extends BaseController {      public function postAuth()     {         //check which submit was clicked on         if(Input::get('login')) {             $this->postLogin(); //if login then use this method         } elseif(Input::get('register')) {             $this->postRegister(); //if register then use this method         }      }          public function postLogin()     {         echo "We're logging in";         //process your input here Input:get('email') etc.     }      public function postRegister()     {         echo "We're registering";         //process your input here Input:get('email') etc.     }  } ?> 
like image 125
ClickCoder Avatar answered Sep 23 '22 21:09

ClickCoder


My solution:

first I set up form with no action

<script>     var baseUrl = "{{ URL::to('/'); }}";    </script>  {{ Form::open(array('url' => '', 'id'=> 'test-form')) }} {{ Form::text('username') }} {{ Form::password('password') }} {{ Form::password('confirm_password') }} <input type="submit" name="login" id="login" value="Login"> <input type="submit" name="register" id="register" value="Register"> {{ Form::close() }} 

for routes (routes.php):

Route::post('test/login', array('uses' => 'TestController@login')); Route::post('test/register', array('uses' => 'TestController@register')); 

controller (TestController.php)

public function login(){     //do something... }  public function register(){     //do something... } 

Jquery: (test.js)

$('form :submit').on('click', function(event){      var a = $(this);     var form = $('form');     var action = a.attr('id');      form.attr('action', baseUrl + '/test/' + action);     form.submit(); }); 
like image 45
angelo Avatar answered Sep 23 '22 21:09

angelo