Generate form validators for Laravel: an extension of way/generators

Overview

Laravel Form Validator

Build Status

Contents

Introduction

After using Jeffrey Way's Generator and his Validator package for a while now I got fed up of copying and pasting the contents of the form validation files so thought I'd create my own version.

What will this do?

This package will create a form validation file containing a list or rules for the validation package to validate.

Why not just folk the generators package?

Well I still only have 3 or 4 clients as a Freelance Web Developer and this gives me the perfect opportunity to show my coding skills off. That way when people ask me if I have any work I can show them it doesn't seem like I'm making excuses when I mention "white label" and "non disclosure agreements".

Installation

Install this package through Composer.

"require-dev": {
    "grandadevans:laravel-form-validator": "~0.1.0"
}

Then include the service provider in your app/config/app.php by adding it to your "providers" array:

/*
 * app/config/app.php
 */
'providers' => array(
    #########
    'Grandadevans\GenerateForm\ServiceProvider\GenerateFormServiceProvider'
);

Don't forget that composer.json will need to know where to autoload the form from. So if the forms are kept in the default app/Forms directory you could just add it to the classMap

/*
 * composer.json
 */
"autoload": {
	"classmap": [
		"app/commands",
		"app/controllers",
		"app/models",
		"app/database/migrations",
		"app/database/seeds",
        
        "app/Forms"
    ]
}

Also: as you have changed the classMap you will have to run

composer dump-autoload

Usage

From the command line you can call the package with

php artisan generate:form

From the root directory of your Laravel installation.

Required Argument

There is only one required argument and that is the name of the form

Options

  • --dir This is the directory in which the form will be saved to (defaults to app/Forms). Please make sure that the directory exists before executing the command.
  • --rules This is a string representation of the rules to be used (see below).
  • --namespace This is the namespace that will be given to the Form.

The Rules Option

This is where the command really comes into it's own. The rules string should be made up of the following

  1. The name of the input field to validate followed by a pipe ( | )
  2. A list of the conditions that the input is to validate against. Each condition being separated by another colon ( pipe* )
  3. If you wish to validate another field then separate them with an ampersand ( & ) and carry on.

Example: If I wanted to validate a typical login form containing a username and password field I would set the rules option as follows

php artisan generate:form Login --rules="username|required|between:6,50|alpha & password|required|min:8"

Each condition that is entered (required, confirmed etc) will be validated against the available conditions in Laravel docs.

Once the command is executed a Form is generated and placed in the specified directory (or the default app/Forms).

Inject and Type hint the generated form into your controller (or where you wish to do your validation)

protected $loginForm;

public function __construct(LoginForm $loginForm)
{
	$this->loginForm = $loginForm;
}

Try to validate the input with

$this->loginForm->validate(Input::only(['username','password']));

Example

Let's say I want to create the above mentioned login form

Step 1: Create the form

php artisan generate|form Login --rules="username|required|between:6,50|alpha & password|required|min:8"

I can then view the form at app/Forms/FooForm.php.

<?php

use Laracasts\Validation;

/**
 *
 * Class LoginForm
 *
 */
class LoginForm extends FormValidator {

    /**
     * The array of rules to be processed
     *
     * @var array
     */
    protected $rules=[
        'username' => 'required|between:6,50|alpha',
        'password' => 'required|min:8',
    ];
}

Step 2: Inject the form into your controller/model

/*
 * app/controllers/LoginController.php
 */
public function LoginController extends BaseController
{

    /**
     * @var LoginForm
     */
    protected $loginForm;
    
    /**
     * @param LoginForm $loginForm
     */
    public function __construct(LoginForm $loginForm)
    {
        $this->loginForm = $loginForm;
    }

Step 3: Validate the input

    
    /**
     * Validate the login details
     */
    public function validateForm()
    {
        $input = Input::only([
            'username',
            'password'
        ]);
        
        try {
            $this->loginForm->validate($input);
        }
        
        catch(\Laracasts\Validation\FormValidationException $e) {
			return Redirect::back()->withInput()->withErrors($e->getErrors());
	}

        
    // Do something with the data
    
}

Tests

During the construction of this package I have carried out testing with

  • PHPSpec - General low level tests
  • Codeception - End to end test used to test from the command
  • PHPUnit - Unit test used to test the command itself using Symfony's CommandTester

I also have travis monitoring the condition of the build for failures and you can check on it's progress by visiting it's Travis CI page

if you want to see the test results navigate to vendor/grandadevans/laravel-form-validator and run

composer install --dev

You can then run the tests individually

./vendor/bin/codecept run acceptance
./vendor/bin phpspec run
./vendor/bin phpunit

or you can run the test script to show all results

./runTests.sh

GitHub and Packagist

You can find this package through Github and Packagist

You might also like...
🏭 An easy way to generate populated factories for models.
🏭 An easy way to generate populated factories for models.

Laravel Populated Factory provides an easy way to generate populated factories for models according to types & names of their columns. Install You can

A simple way to generate files from stubs.

STUBBY A simple way to generate files from stubs. Usage For example we have a stub file that looks like this: ?php namespace {{ namespace }}; use A

Laravel Form builder for version 5+!

Laravel 5 form builder Form builder for Laravel 5 inspired by Symfony's form builder. With help of Laravels FormBuilder class creates forms that can b

Razorpay payment gateway integration in laravel with submit form and storing details in payment table.

Integrating razorpay payment gateway in laravel with submit form and storing payment details in payment table. How to settup the project in your local

Laravel Livewire form component with declarative Bootstrap 5 fields and buttons.

Laravel Livewire Forms Laravel Livewire form component with declarative Bootstrap 5 fields and buttons. Requirements Bootstrap 5 Installation composer

🧙‍♀️ Arcanist takes the pain out of building multi-step form wizards in Laravel.
🧙‍♀️ Arcanist takes the pain out of building multi-step form wizards in Laravel.

Installation Arcanist requires PHP 8 and Laravel 8. composer require laravel-arcanist/arcanist Documentation You can find the full documentation here

Reactive Form Builder for Vue.js with Laravel Support
Reactive Form Builder for Vue.js with Laravel Support

Dynamic Form Builder for Laravel with Vue.js Create even the most complex forms with ease, using two-sided validation, eloquent, nested elements, cond

A TALL-based Laravel Livewire component to replace the (multiple) select HTML input form with beautiful cards.
A TALL-based Laravel Livewire component to replace the (multiple) select HTML input form with beautiful cards.

TALL multiselect cards A TALL-based Laravel Livewire component to replace the (multiple) select HTML input form with beautiful cards. Table of content

Rapid form generation with Bootstrap 3 and Laravel.

Important: This package is not actively maintained. For bug fixes and new features, please fork. BootForms BootForms builds on top of my more general

Owner
John Evans
From British Soldier -> Businessman -> Worlds-worst Businessman -> Good Back-end Web Developer -> Software Engineer -> Cripple -> Disabled YouTuber
John Evans
Laravel Livewire (TALL-stack) form generator with realtime validation, file uploads, array fields, blade form input components and more.

TALL-stack form generator Laravel Livewire, Tailwind forms with auto-generated views. Support Contributions Features This is not an admin panel genera

TinaH 622 Jan 2, 2023
Validate your input data in a simple way, an easy way and right way. no framework required. For simple or large. project.

wepesi_validation this module will help to do your own input validation from http request POST or GET. INTEGRATION The integration is the simple thing

Boss 4 Dec 17, 2022
Composer package which adds support for HTML5 elements using Laravels Form interface (e.g. Form::date())

Laravel HTML 5 Inputs Composer package which adds support for HTML5 elements by extending Laravel's Form interface (e.g. Form::date()) Adds support fo

Small Dog Studios 11 Oct 13, 2020
A collection of generators for Lumen and Laravel 5.

Lumen generators A collection of generators for Lumen and Laravel 5. Contents Why ? Installation Quick Usage Detailed Usage Model Generator Migration

Amine Ben hammou 349 Mar 24, 2022
Rapidly speed up your Laravel workflow with generators

Fast Workflow in Laravel With Custom Generators This Laravel package provides a variety of generators to speed up your development process. These gene

Jeffrey Way 22 Oct 28, 2022
Laracademy Generators - is a tool set that helps speed up the development process of a Laravel application.

Laracademy Generators Laracademy Generators - is a tool set that helps speed up the development process of a Laravel application. Author(s): Laracadem

Laracademy 320 Dec 24, 2022
Laravel File Generators with config and publishable stubs

Laravel File Generators Custom Laravel File Generators with a config file and publishable stubs. You can publish the stubs. You can add your own stubs

Ben-Piet O'Callaghan 116 Oct 29, 2022
Chrome extension to generate Laravel integration tests while using your app.

Laravel TestTools Check out the introduction post about the chrome extension. Installation git clone [email protected]:mpociot/laravel-testtools.git # i

Marcel Pociot 473 Nov 1, 2022
Otpify is a Laravel package that provides a simple and elegant way to generate and validate one time passwords.

Laravel Otpify ?? Introduction Otpify is a Laravel package that provides a simple and elegant way to generate and validate one time passwords. Install

Prasanth Jayakumar 2 Sep 2, 2022
Generate trends for your models. Easily generate charts or reports.

Laravel Trend Generate trends for your models. Easily generate charts or reports. Support us Like our work? You can support us by purchasing one of ou

Flowframe 139 Dec 27, 2022