AppDividend
Latest Web Development Tutorials

Laravel 5.5 Validation Example From Scratch

Laravel Validation

1,538

Laravel 5.5 Validation Example From Scratch is the topic; we will cover today. Laravel 5.5 has officially released and ships with one validation feature called Custom Validation Rules.

Laravel 5.5 Install

If you have installed composer, then type the following command to install latest Laravel Framework version.

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

Step 1: Configure the database.

Edit the .env file and put your MySQL credentials detail in the database.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel55validation
DB_USERNAME=root
DB_PASSWORD=mysql

Now, run the following command to create the two tables.

php artisan migrate

Step 2: Create controllers and models.

Make one Controller file for our project by the following command.

php artisan make:controller ItemController --resource

Make one model and migration for our small task.

php artisan make:model Item -m

Create a schema for our items table.

// create_items_table

<?php

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->string('avatar');
            $table->timestamps();
        });
    }

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

Now, type the following command to run the migration file.

php artisan migrate

Step 3: Make one form view to enter the item details.

Make one view file inside resources  >>  views  >>  items.blade.php file.

<!-- items.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')}}">
        {{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>
        <div class="form-group">
          <label for="price">Upload an image:</label>
          <input type="file" name="image">
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
      </form>
    </div>
  </body>
</html>

Step 4: Define the routes for our application in the web.php file.

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

// web.php

Route::resource('items', 'ItemController');




Now, we need to define the attributes in the model file to prevent mass assignment exceptions.

// Item.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    protected $fillable = ['name', 'price', 'image'];
}

Next step, we need to display the form. So in ItemController.php file, put the following code in the create() function.

// ItemController.php

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

Now, start the Laravel development server by the following command.

php artisan serve

Go to this URL: http://localhost:8000/items/create

Laravel 5.5 Validation

Step 5: Writing The Validation Logic

// ItemController.php

  /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $items = $request->validate([
          'name' => 'required',
          'price'=> 'required|numeric',
          'image'=> 'required'
        ]);
        $items->save();
        return back();
    }

If the validation rules pass then our code executes normally. If validation fails, then an exception will be thrown, and proper error response will automatically be added.

Displaying The Validation Errors

If the validation rules fail then all of the validation errors automatically flashed to the sessions. We can access the validation messages via $errors variable. 

The $errors variable is bound to all the views because Illuminate\View\Middleware\ShareErrorsFromSession middleware is applied in $errors variable and this middleware is defined in the web routes. So, when the validation fails then $errors variable filled with the error responses and since it is flashed only one time we can see in the view. When you refresh the page, the $errors variable will empty.

<!-- items.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">
      @if ($errors->any())
          <div class="alert alert-danger">
              <ul>
                  @foreach ($errors->all() as $error)
                      <li>{{ $error }}</li>
                  @endforeach
              </ul>
          </div><br />
      @endif
      <form method="post" action="{{url('items')}}">
        {{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>
        <div class="form-group">
          <label for="price">Upload an image:</label>
          <input type="file" name="image">
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
      </form>
    </div>
  </body>
</html>

 

Laravel Validation Example From Scratch

Stopping On First Validation Failure

Related Posts
1 of 8

If we want to stop the execution of code at the time of the first validation rule failure then we need to use bail attribute in an array.

// ItemController.php

$request->validate([
    'name' => 'bail|required|max:255',
    'price' => 'required',
    'image' => 'required'
]);

Here, when name attribute fails the validation, required and max attributes will not check and we redirect to the home page with only required attribute’s validation message.

Form Request Validation

If your validation rules get complex then this might be the solution for your application. Form requests are custom request class that contain validation logic.

We can create FormRequest class using the following command.

php artisan make:request ItemRequest

Now, go to the app  >>  Http  >>  Requests  >>  ItemRequest.php file and  place the rules in an array.

Also, make function authorize return true, otherwise auth fails and an exception will be thrown.

// ItemRequest.php

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

Fill the rules array with the validation rules.

// ItemRequest.php

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

Now, include this file into our ItemController.php file.

// ItemController.php

use App\Http\Requests\ItemRequest;

  /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(ItemRequest $request)
    {
        $items = $request->all();
        $items->save();
        return back();
    }

Inject ItemRequest class in the store method and just then if the rules array defined in ItemRequest class passes the validation then it will store in the database, otherwise not.

Customizing The Error Messages

If we want to customize the error messages then we need to override the messages() method into the ItemRequest class.

// ItemRequest.php

/**
 * Get the error messages for the defined validation rules.
 *
 * @return array
 */
public function messages()
{
    return [
        'name.required' => 'A name attribute is required',
        'price.required'  => 'A price attribute is required',
        'image.required' => 'An image attribute is required'
    ];
}

Now, when you submit the form with out filling any data then you will see these messages and not default messages.



There are so many validation rules that you can check it over here. It is Laravel’s official documentation.

Custom Validation Rules

We need to create one rule file for this validation.

Using Rule Objects

If you want to specify your own rules then we can use the following command to generate our own rule.

php artisan make:rule FiveCharacters

This command will create a directory called rules and in then we can use this new file to define our own rules and messages.

// FiveCharacters.php
<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class FiveCharacters implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return strlen($value) === 5;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be 5 characters';
    }
}

In the ItemController.php file, we need to import this rule and use it.

// ItemController.php

use App\Rules\FiveCharacters;

/**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $items = $request->validate([
            'name' => [new FiveCharacters],
        ]);
        $items->save();
        return back();
    }

 

Custom Rule Validation In Laravel 5.5

Finally, Laravel 5.5 Validation Example post is over.

You can check out this article about Laravel 5.5 CRUD Tutorial:

Laravel 5.5 Tutorial With Example From Scratch

If you have any doubt in this Laravel Validation Tutorial then ask in a comment below

3 Comments
  1. Shiro says

    How do you validate all the checkbox need to be checked?

  2. ryan says

    please list out what’s new in laravel 5.5

Leave A Reply

Your email address will not be published.