Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views :
InvestmentNovel

Latest Programming Tutorial Blog

Laravel 5.6 Validation Example From Scratch

/
/
/
103 Views

Hello developers, In this tutorial, I will explain to you how to do Laravel 5.6 Validation Example From Scratch. Laravel gives several different approaches to validate your application’s incoming data. There are various validation rules that you can check it over here. It is Laravel’s official documentation.

Laravel 5.6 Validation Example From Scratch

We are going to Configure Laravel Project.

#1: Download Laravel Project

Install new Laravel project by the writing following command.

composer create-project --prefer-dist laravel/laravel 5.6 validation

#2: Configure SQL Database

Now we can setup database credentials.

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

#3: Build Model and Migration File

php artisan make:model Cryptocurrency -m

It will create a Cryptocurrency.php file and also create a create_cryptocurrencies_table.php  migration file.

// create_cryptocurrencies_table

public function up()
    {
        Schema::create('cryptocurrencies', function (Blueprint $table) {
            $table->increments('id');
            $table->string('cryptocurrenciename');
            $table->integer('cryptocurrencieprice');
            $table->string('photo');
            $table->timestamps();
        });
    }

Save and run.

php artisan migrate

#4: Create a View File

Create a file in resources  >>  views  >>   Cryptocurrency.blade.php and put this following code in it.

<!-- cryptocurrency.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel 5.6 Validation Example From Scratch</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">  
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>    </head>
  <body>
    <div class="container">
      <h2>Laravel 5.6 Validation Example From Scratch</h2><br/>
      <form method="post" action="{{url('cryptocurrency/store')}}" enctype="multipart/form-data">
        @csrf
        <div class="form-group row">
            <label for="cryptocurrencyname" class="col-md-4 col-form-label text-md-right">Cryptocurrency Name:</label>
            <div class="col-md-2">
                <input id="cryptocurrencyname" type="text" class="form-control" name="cryptocurrencyname">
            </div>
        </div>
        <div class="form-group row">
            <label for="cryptocurrencyprice" class="col-md-4 col-form-label text-md-right">Cryptocurrency Price:</label>
            <div class="col-md-2">
                <input id="cryptocurrencyprice" type="text" class="form-control" name="cryptocurrencyprice">
            </div>
        </div>
        <div class="form-group row">
          <div class="col-md-4"></div>
          <div class="col-md-2">
            <input type="file" name="photo">    
         </div>
        </div>
        <div class=" form-group row">
          <div class="col-md-4"></div>
          <div class="col-md-2">
            <button type="submit" class="btn btn-success">Submit</button>
          </div>
        </div>
      </form>
    </div>
  </body>
</html>

#5: Create one controller

 php artisan make:controller CryptocurrencyController

It will build a controller file called PostController.php.

public function create()
    {
        return view('cryptocurrency');
    }

#6: Define Route

We register all route in a web.php file.

Route::get('cryptocurrency','CryptocurrencyController@create');
Route::post('cryptocurrency/store','CryptocurrencyController@store');

 #7: Writing The Validation Logic

Next, we are ready to fill in our store () method with the logic to validate the cryptocurrency. To do that, we will use the validate method provided by the Illuminate\Http\Request object. If validation breaks, an exception will be thrown. If the validation rules pass, your code will keep executing normally.

//CryptocurrencyController.php

 public function store(Request $request)
    {
        $validatedData = $request->validate([
            'cryptocurrencyname' => 'required|max:25',
            'cryptocurrencyprice' => 'required|numeric',
            'photo' => 'required|image'
        ]);    
    }

#8: Displaying The Validation Errors

So, what if the incoming request parameters do not pass the provided validation rules? As mentioned previously, Laravel will automatically redirect the user back to their past location. We can access the validation messages through $errors variable. 

<!-- cryptocurrency.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel 5.6 Validation Example From Scratch</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">  
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>    </head>
  <body>
    <div class="container">
      <h2>Laravel 5.6 Validation Example From Scratch</h2><br/>
      @if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
      @endif
      <form method="post" action="{{url('cryptocurrency/store')}}" enctype="multipart/form-data">
        @csrf
        <div class="form-group row">
            <label for="cryptocurrencyname" class="col-md-4 col-form-label text-md-right">Cryptocurrency Name:</label>
            <div class="col-md-2">
                <input id="cryptocurrencyname" type="text" class="form-control" name="cryptocurrencyname">
            </div>
        </div>
        <div class="form-group row">
            <label for="cryptocurrencyprice" class="col-md-4 col-form-label text-md-right">Cryptocurrency Price:</label>
            <div class="col-md-2">
                <input id="cryptocurrencyprice" type="text" class="form-control" name="cryptocurrencyprice">
            </div>
        </div>
        <div class="form-group row">
          <div class="col-md-4"></div>
          <div class="col-md-2">
            <input type="file" name="photo">    
         </div>
        </div>
        <div class=" form-group row">
          <div class="col-md-4"></div>
          <div class="col-md-2">
            <button type="submit" class="btn btn-success">Submit</button>
          </div>
        </div>
      </form>
    </div>
  </body>
</html>

laravel custom validation rule example

#9: Stopping On First Validation Failure

Sometimes you may want to stop running validation rules on an attribute after the first validation failure. To make, assign the bail rule to the attribute:

//CryptocurrencyController.php

 public function store(Request $request)
    {
        $validatedData = $request->validate([
            'cryptocurrencyname' => 'bail|required|max:25',
            'cryptocurrencyprice' => 'required|numeric',
            'photo' => 'required|image'
        ]);    
    }

Here, when cryptocurrencyname attribute fails the validation, required and max attributes will not check and we redirect on the home page with particularly required attribute’s validation message.

#10: Form Request Validation

If your validation rules more complex then you may wish to create a “form request”.  Form requests are custom request classes that contain validation logic. Type following command in cmd.

php artisan make:request CryptocurrencyRequest

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

Moreover, do function authorize return true, otherwise, auth fails and an exception will be thrown.

// CryptocurrencyRequest.php

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

Appoint the rules array with the validation rules.

// CryptocurrencyRequest.php

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

Now, add this file in our CryptocurrencyController.php file.

//CryptocurrencyController.php

use App\Http\Requests\CryptocurrencyRequest;

public function store(CryptocurrencyRequest $request)
{
        $validated = $request->validated();
}

#11: Customizing The Error Messages

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

// CryptocurrencyRequest.php

public function messages()
    {
         return [
                    'cryptocurrencyname.required' => 'A cryptocurrencyname is required',
                    'cryptocurrencyname.max' => 'A cryptocurrencyname must be 25 character or less',
                    'cryptocurrencyprice.required'  => 'A cryptocurrencyprice is required',
                    'cryptocurrencyprice.numeric' => 'A cryptocurrencyprice must be a numeric',
                    'photo.required'  => 'A photo is required',
                    'photo.image'  => 'A photo must be an image'
                 ];
    }

laravel 5.6 validation rules example

At last, our Laravel 5.6 Validation Example From Scratch is over.

  • Facebook
  • Twitter
  • Google+
  • Linkedin
  • Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This div height required for enabling the sticky sidebar