Laravel 5 and simple Forms workaround

Here is a simple example of using laravel 5 powerful forms to deliver a secure and fast result!
To make our lives easier we need to install the HTML package!

In file /compojer.json we add:
"require": {
"laravel/framework": "5.0.*",
"laravelcollective/html": "~5.0"
},

Next add the service provider and aliases.
In /config/app.php we update the following:

'providers' => [
'Illuminate\Html\HtmlServiceProvider',
],

'aliases' => [
'Form'=> 'Illuminate\Html\FormFacade',
'HTML'=> 'Illuminate\Html\HtmlFacade',
],

From command line run (while in your project’s folder):

composer update

NOW WE ARE READY TO USE HTML PACKAGE for forms.
Steps for a simple workaround:
1. Create Model/migration

php artisan make:model Item (table in migration file is named 'items')

Create your table columns in the migration file that is automatically generated under /database/migrations
In the model (Item.php) do not forget to declare which columns/fields will be accessible!

protected $fillable = ['column1', 'column2']

2. Create Controller

php artisan make:controller ItemController

In the controller we add as a method parameter the formrequest and you include the form request (we create it in step 5):

use appname\Http\Requests\ItemFormRequest;

public function method(ItemFormRequest $request){}

3. Create add item view file

{!! Form::open(array('method' => 'put', 'url' => ['item/method'], 'class' => 'form-inline')) !!}

{!! Form::label('Field Label') !!}
{!! Form::text('column1', null,
array('required', 'class'=>'form-control',
'placeholder'=>'placeholder for field 1')) !!}

{!! Form::close() !!}

item/method is the method from the ItemController that we want to serve the form request.

4. Create update view file

Form fields are populated from values from the model $item variable automatically.

{!! Form::model($item, array('method' => 'put', 'url' => ['item/method'], 'class' => 'form')) !!}

{!! Form::label('Field Label') !!}
{!! Form::text('column1', null,
array('required', 'class'=>'form-control',
'placeholder'=>'placeholder for field 1')) !!}

{!! Form::close() !!}

item/method is the method from the ItemController that we want to serve the form request.

5. Create form request

php artisan make:request ItemFormRequest

It containes rules for form validation.
It is saved under folder /app/Http/Requests

And you are ready to go!!!



Polyvios Damianakis

Polyvios Damianakis

Biography to be completed

More Posts - Website

Follow Me:
LinkedIn