Forms in Laravel

While we can generate forms by writing html tags directly, most of us would prefer using the Laravel packages for this purpose.

We will start by installing the Html package.

C:\wamp\www\laraveltest>    composer require “laravelcollective/html”:”^5.2.0″

This will install the html package.

Now enter the new provider and alias in app.php in the config directory.


<?php return [ /* |-------------------------------------------------------------------------- | Application Name |-------------------------------------------------------------------------- | | This value is the name of your application. This value is used when the | framework needs to place the application's name in a notification or | any other location as required by the application or its packages. */ 'name' => env('APP_NAME', 'Laravel'),

/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services your application utilizes. Set this in your ".env" file.
|
*/

'env' => env('APP_ENV', 'production'),

/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/

'debug' => env('APP_DEBUG', false),

/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/

'url' => env('APP_URL', 'http://localhost'),

/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/

'timezone' => 'UTC',

/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/

'locale' => 'en',

/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/

'fallback_locale' => 'en',

/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/

'key' => env('APP_KEY'),

'cipher' => 'AES-256-CBC',

/*
|--------------------------------------------------------------------------
| Logging Configuration
|--------------------------------------------------------------------------
|
| Here you may configure the log settings for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Settings: "single", "daily", "syslog", "errorlog"
|
*/

'log' => env('APP_LOG', 'single'),

'log_level' => env('APP_LOG_LEVEL', 'debug'),

/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/

'providers' => [

/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,

/*
* Package Service Providers...
*/
Laravel\Tinker\TinkerServiceProvider::class,

/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
<strong>Collective\Html\HtmlServiceProvider::class,</strong>

],

/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/

'aliases' => [

'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
'Bus' => Illuminate\Support\Facades\Bus::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
'Cookie' => Illuminate\Support\Facades\Cookie::class,
'Crypt' => Illuminate\Support\Facades\Crypt::class,
'DB' => Illuminate\Support\Facades\DB::class,
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
'Event' => Illuminate\Support\Facades\Event::class,
'File' => Illuminate\Support\Facades\File::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
'Notification' => Illuminate\Support\Facades\Notification::class,
'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class,
'Redis' => Illuminate\Support\Facades\Redis::class,
'Request' => Illuminate\Support\Facades\Request::class,
'Response' => Illuminate\Support\Facades\Response::class,
'Route' => Illuminate\Support\Facades\Route::class,
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
<strong>'Form' => Collective\Html\FormFacade::class,</strong>
<strong> 'Html' => Collective\Html\HtmlFacade::class,</strong>

],

];

&nbsp;

 

Then create a new view in the Resources directory.


<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Form Practice</title>
{{ Html::style('css/w3.css') }}
</head>
<body>
<div class="flex-center position-ref full-height">
<h1>Post Form</h1>
{{ Form::open(array('url' => 'practiceform')) }}

{{ Form::close() }}
</div>
</body>
</html>

&nbsp;

Let us view this page in the browser and also its source in the browser.

 


<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Form Practice</title>
<link media="all" type="text/css" rel="stylesheet" href="http://localhost/laraveltest/public/css/w3.css">

</head>
<body>
<div class="flex-center position-ref full-height">
<h1>Post Form</h1>
<form method="POST" action="http://localhost/laraveltest/public/practiceform" accept-charset="UTF-8"><strong><input name="_token" type="hidden" value="nBX8fQILg8MJ401GOAEGj0TDseS5I5OGJr4YQM9X"></strong>

</form>
</div>
</body>
</html>

 

Read up the bold part. This is the cross-site request forgery (CSRFtoken auto generated by Laravel. It is tested by the Kernel.php file in

app/html


<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];

/**
* The application's route middleware groups.
*
* @var array
*/
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',
],
];

/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}

 

To create a textbox we use

{{Form::text(’email’, ‘champakroyVaranasi@superfastmail.com’,array(‘class’ => ‘w3-card’,’title’=>’Enter EMail Here’))}}

The first part ’emal’ is the name of the text box.
the next part is the default value ‘champakroyVaranasi@superfastmail.com’.
all other attributes will be added to the array. In this case a css class and a titile.
The generated code is


<input class="w3-card" title="Enter EMail Here" name="email" type="text" value="champakroyVaranasi@superfastmail.com" id="email">

The id , name and everything else can be changed from the array parameters.


{{Form::text('email', 'champakroyVaranasi@superfastmail.com',array('class' => 'w3-card','title'=>'Enter EMail Here','name'=>'newemail','id'=>'t1'))}}


<input class="w3-card" title="Enter EMail Here" name="newemail" id="t1" type="text" value="champakroyVaranasi@superfastmail.com">


<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Form Practice</title>
{{ Html::style('css/w3.css') }}
</head>
<body class="w3-padding">
<div class="w3-teal w3-card">
<h1>Post Form</h1>
{{ Form::open(array('url' => 'practiceform')) }}
<br/>
{{Form::label('email', 'E-Mail Address')}}
<br/>
{{Form::text('email', 'champakroyVaranasi@superfastmail.com',array('class' => 'w3-card','title'=>'Enter EMail Here','name'=>'newemail','id'=>'t1'))}}

<br/>

{{Form::password('password')}}
<br/>

Checkbox with name and value
{{Form::checkbox('chkname', 'chkvalue')}}
<br/>
Radio Button
{{Form::radio('radionme', 'radiovalue')}}
<br/>
Checked Checkbox and Radio Button
{{Form::checkbox('chkname', 'chkvalue', true)}}
<br/>
{{Form::radio('radioname', 'radiovalue', true)}}

<br/>
File Input Control
{{Form::file('resume')}}

<br/>

Dropdown List
{{Form::select('cities', array('BSB' => 'Varanasi', 'LKO' => 'Lucknow','KNP'=>'Kanpur'))}}
<br/>
Drop-Down List With Selected value
{{Form::select('cities', array('BSB' => 'Varanasi', 'LKO' => 'Lucknow','KNP'=>'Kanpur'), 'LKO')}}
<br/>
Grouped List
{{Form::select('cities', array(
'UP' => array('BSB' => 'Varanasi','LKO'=>'Lucknow','KNP'=>'Kanpur'),
'MP' => array('BHP' => 'Bhopal','STN'=>'Satna','JBL'=>'Jabalpur'),
),'BHP')}}
<br/>
Range List
{{Form::selectRange('number', 10, 20)}}
<br/>
Month Names with July=7 selected
{{Form::selectMonth('month','7')}}

<br/>







{{ Form::close() }}
</div>
</body>
</html>

View source


&nbsp;

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Form Practice</title>
<link media="all" type="text/css" rel="stylesheet" href="http://localhost/laraveltest/public/css/w3.css">

</head>
<body class="w3-padding">
<div class="w3-teal w3-card">
<h1>Post Form</h1>
<form method="POST" action="http://localhost/laraveltest/public/practiceform" accept-charset="UTF-8"><input name="_token" type="hidden" value="vgkPXZzwhoQeGE2vRQgVebOpY44kQAxbRJ5Ewqim">
<br/>
<label for="email">E-Mail Address</label>
<br/>
<input class="w3-card" title="Enter EMail Here" name="newemail" id="t1" type="text" value="champakroyVaranasi@superfastmail.com">

<br/>

<input name="password" type="password" value="">
<br/>

Checkbox with name and value
<input name="chkname" type="checkbox" value="chkvalue">
<br/>
Radio Button
<input name="radionme" type="radio" value="radiovalue">
<br/>
Checked Checkbox and Radio Button
<input checked="checked" name="chkname" type="checkbox" value="chkvalue">
<br/>
<input checked="checked" name="radioname" type="radio" value="radiovalue">

<br/>
File Input Control
<input name="resume" type="file">

<br/>

Dropdown List
<select name="cities"><option value="BSB">Varanasi</option><option value="LKO">Lucknow</option><option value="KNP">Kanpur</option></select>
<br/>
Drop-Down List With Selected value
<select name="cities"><option value="BSB">Varanasi</option><option value="LKO" selected="selected">Lucknow</option><option value="KNP">Kanpur</option></select>
<br/>
Grouped List
<select name="cities"><optgroup label="UP"><option value="BSB">Varanasi</option><option value="LKO">Lucknow</option><option value="KNP">Kanpur</option></optgroup><optgroup label="MP"><option value="BHP" selected="selected">Bhopal</option><option value="STN">Satna</option><option value="JBL">Jabalpur</option></optgroup></select>
<br/>
Range List
<select name="number"><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option><option value="18">18</option><option value="19">19</option><option value="20">20</option></select>
<br/>
Month Names with July=7 selected
<select name="month"><option value="1">January</option><option value="2">February</option><option value="3">March</option><option value="4">April</option><option value="5">May</option><option value="6">June</option><option value="7" selected="selected">July</option><option value="8">August</option><option value="9">September</option><option value="10">October</option><option value="11">November</option><option value="12">December</option></select>

<br/>







</form>
</div>
</body>
</html>

 

 

Leave a Reply