Form Submission in Laravel

This post is an introduction to form submission in laravel using get and post. We will create forms and access parameters using the get and post methods.
Let us start with submitting a form via the get method. We have created a php page called form.php which has 2 forms. One submitted via method=”get” while the other is via method=”post”


<h1>Get Form</h1>
<form method="get" action="addform">
n1<input type="text" name="n1"/>
<br/>
n2<input type="text" name="n2"/>
<br/>
<input type="submit" value="Go"/>
</form>
<h1>Post Form</h1>
<form method="post" action="addform">

 

n1<input type="text" name="n1"/>
<br/>
n2<input type="text" name="n2"/>
<br/>
<input type="submit" value="Go"/>
</form>

The submitted form data will be accessed at the url  addform

So, we have added the following routes to web.php under routes


use Illuminate\Http\Request;
Route::get('/addform', function (Request $request) {
$n1=$request['n1'];
$n2=$request['n2'];
$sum=$n1+$n2;
return 'get' . $sum;
});
Route::post('/addform', function (Request $request) {
$n1=$request['n1'];
$n2=$request['n2'];
$sum=$n1+$n2;
return 'post' . $sum;
});

Read the above code carefully.

We are importing the Request object from the following URL.

use Illuminate\Http\Request;

Then.


Route::get('/addform', function (Request $request) {
 $n1=$request['n1'];
 $n2=$request['n2'];
 $sum=$n1+$n2;
 return 'get' . $sum;
});

The function is defined as

Route::get(‘/addform’, function (Request $request) {

The url is at /addform, method is get.

The form data is accessed using the same old Php syntax(other methods are available).

Post form

The post form will need validation via the csrf_field(). We will bypass it for now by commenting the relevant code in Kernel.php under app/Http


protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
<strong>// \App\Http\Middleware\VerifyCsrfToken::class,</strong>
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],

'api' => [
'throttle:60,1',
'bindings',
],
];

 

Two things next. Analyzing the response object in detail and then views.

 

Leave a Reply