Laravel 5 Validation Example From Scratch

Today, Laravel 5 validation example is our main topic and let’s discuss it with some examples. Laravel is the fastest growing PHP MVC Framework, which provides us fluent API to build our web application and so we have also an API about Validate our form requests. If you are new to Laravel 5.4 then check out my this article Laravel 5.4 CRUD example from scratch

Step 1: Create project of Laravel 5 Validation

composer create-project laravel/laravel demoValidation --prefer-dist

That command will install Laravel project, and next would be to edit the .env file to update your database credentials. Now go to terminal and type 

php artisan migrate

It will create two tables for us in the database.

Step 2: Make model Item.php of our project Laravel Validation

We need to validate our items table in our database, so we need to create one model and one migration for that. So, go to the terminal and type following command.

php artisan make:model Item -m

It will create both Item model as well as create_items_table.

Now, create a controller for Items table

php artisan make:controller ItemController --resource

It will create one controller file with the boilerplate in it.

Step 3: Generate database migrations for items table.

Now, we need to define the database fields in migration. So go to the database >> migrations >> create_migration_table and put the following code in it.

<?php

// create_items_table

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('price');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('items');
    }
}




Go to the terminal and type

php artisan migrate

Step 4: Make view file for Laravel Form Validation.

We need to create one view for forms, and then we need to submit that form to our server and check against our validation rules. If any of the rules does not fulfill our requirement, then we need to display an error.

Go to the routes file routes >> web.php and add the following code in it.

// web.php

Route::get('items/add', 'ItemController@create');
Route::post('items/add', 'ItemController@store');

Go to the ItemController file and add the following code in create function.

// ItemController.php

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('itemForm');
    }

Step 5: Made view on Laravel 5.4 Form Validation

I have created one view file inside resources >> views >> itemForm.blade.php

<!-- itemForm.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Item Validation Form</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
  </head>
  <body>
    <div class="container">
      <form method="post" action="{{url('items/add')}}">
        {{csrf_field()}}
        <div class="form-group">
          <label for="itemName">Item Name:</label>
          <input type="text" class="form-control" id="itemName" name="name">
        </div>
        <div class="form-group">
          <label for="price">Price:</label>
          <input type="text" class="form-control" id="price" name="price">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
    </div>
  </body>
</html>

Step 6: Mass Assignment Exception

Possible Errors

Mass assignment exception in Laravel

Possible Solutions

Go to your database table related model and put the following code in it. In my case,  it is an Item.php

// Item.php

protected $fillable = ['name', 'price'];

This will resolve  Mass assignment exception

If you do not define the table name in Model, then Laravel will assume that you have created table “items” because my model name is Item.php. So Laravel always gives table name plural and model name singular. Perfect naming convention in Object Orientated Relational Mapping.

Step 7: Make validation rule in ItemController.php file. 

Now we are going to define very simple validation rule against our form fields. So go to the ItemController.php file and put the following code in store function.  It will automatically redirect to form page if any of the rules gets failed.

Read More
1 of 4
// ItemController.php

public function store(Request $request)
{
        $this->validate($request, [
        'name' => 'required|max:10',
        'price' => 'required',
        ]);

        Item::create([
          'name' => $request->get('name'),
          'price'=> $request->get('price')
        ]);

        return back()->with('success', 'You have just created one item');
}

Controller class of Laravel is by default provides us validate method, which takes two arguments.

  1. $request
  2. Our validation rules array

If any of the rules are failed, then It will store an array of the errors and puts into flash session. So in form page, we can get that errors object by calling $errors->all()

So we need to display error in itemForm.blade.php

<!-- itemForm.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Item Validation Form</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
  </head>
  <body>
    <div class="container">
      <br />
      @if ($errors->any())
          <div class="alert alert-danger">
              <ul>
                  @foreach ($errors->all() as $error)
                      <li>{{ $error }}</li>
                  @endforeach
              </ul>
          </div>
        @endif

        @if (\Session::get('success'))
            <div class="alert alert-success">
                <p>{{ \Session::get('success') }}</p>
            </div>
        @endif      

      <form method="post" action="{{url('items/add')}}">
        {{csrf_field()}}
        <div class="form-group">
          <label for="itemName">Item Name:</label>
          <input type="text" class="form-control" id="itemName" name="name">
        </div>
        <div class="form-group">
          <label for="price">Price:</label>
          <input type="text" class="form-control" id="price" name="price">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
    </div>
  </body>
</html>




Now go to the form page by typing URL: http://localhost:8000/items/add 

Do not fill any data and submit the form. You will get some errors like this.

Laravel 5.4 validation example from scratch

 

This is flash session so after refreshing the page; validation errors are gone. If everything is correct, then you can see the form page that Item is created.

Step 8: Form Request Validation In Laravel 5.4

For more complex validation scenarios, you may wish to create a “form request.” Form requests are custom request classes that contain validation logic. Create a form request class, use the make:request Artisan CLI command:

php artisan make:request FormRequest

Now, we will use the second example, where we do not use validate() function provided by laravel in the controller, we just pass this FormRequest class as a Dependency Injection.

First, we make another controller called FormController

php artisan make:controller FormController --resource

We need to create two more routes for out application.

// web.php

Route::get('formitem/add', 'FormController@create');
Route::post('formitem/add', 'FormController@store');

Now, we need to create one another view called RequestForm.blade.php

<!-- RequestForm.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Item Validation Form</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
  </head>
  <body>
    <div class="container">
      <br />
      @if ($errors->any())
          <div class="alert alert-danger">
              <ul>
                  @foreach ($errors->all() as $error)
                      <li>{{ $error }}</li>
                  @endforeach
              </ul>
          </div>
        @endif
        @if (\Session::get('success'))
            <div class="alert alert-success">
                <p>{{ \Session::get('success') }}</p>
            </div>
          @endif
      <form method="post" action="{{url('formitem/add')}}">
        {{csrf_field()}}
        <div class="form-group">
          <label for="itemName">Item Name:</label>
          <input type="text" class="form-control" id="itemName" name="name">
        </div>
        <div class="form-group">
          <label for="price">Price:</label>
          <input type="text" class="form-control" id="price" name="price">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
    </div>
  </body>
</html>

Code the FormController function to return a RequestForm view.

// FormController.php

  /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('RequestForm');
    }

Now, we just need to pass FormRequest as a dependency to the store function of the FormController class.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Item;
use App\Requests\FormRequest;

class FormController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('RequestForm');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(FormRequest $request)
    {
        Item::create([
          'name' => $request->get('name'),
          'price'=> $request->get('price')
        ]);
        return back()->with('success', 'You have just created one item');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

Now, only remaining the thing is that to code the FormRequest file, which is in the app >> Http >> Requests >> FormRequest.php Fill the array of rules function with the validation field.

<?php

// FormRequest.php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class FormRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required',
            'price' => 'required'
        ];
    }
}

Now, go to the following URL: http://localhost:8000/formitem/add

Submit the data without fill the form, and you will get the errors and form will not submit.

For more Validation rules, you can find on official Laravel website.

I have put Laravel 5 validation example from scratch code on GitHub

Github Link: https://github.com/KrunalLathiya/Laravel54Validation

Steps to use Github code

  1. Clone the repo in your local.
  2. Go to the root of the project and run command “composer update
  3. Edit .env file and use your MySQL database credentials.
  4. Run the command “php artisan migrate
  5. Now, we need to bootstrap Laravel server so run “php artisan serve
  6. If now go to this URL: http://localhost:8000/items/add

If you still have doubt in this tutorial, then ask in the comment below, I am happy to help you out.

You might also like More from author

1 Comment

  1. Jody says

    You are cool mate, hope you keep it up with laravel tutorial. Thanks a lot

Leave A Reply

Your email address will not be published.