Laravel Form Validation Example From Scratch

Laravel Form Validation Example From Scratch

Laravel 5.7 Form Validation Tutorial From Scratch. Today In this tutorial, we will learn how to validate form in laravel 5.7 application step by step simple and easy way.
And this example also work with laravel 5.8 version.

Every laravel project has many form and diffent diffent type of validation rules required. we will share with you some of daily uses validation rules in laravel provide.

Laravel 5.7 Provide many new form validation features. Here we will tell you each things step by step. Just follow few steps and validate form request with validation
.message.

Laravel Form Validation Example From Scratch

  • Install Laravel 5.7 App
  • Setup Database
  • Make Route
  • Create Controller & Methods
  • Create Blade View
  • Start Development Server
  • Conclusion

Install Laravel App

First of we need to download laravel fresh setup. Use the below command and download fresh new laravel setup :

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

Setup Database

After successfully install laravel 5.7 Application, Go to your project .env file and set up database credential and move next step :

 DB_CONNECTION=mysql 
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name here
DB_USERNAME=here database username here
DB_PASSWORD=here database password here
Migration

If You will download laravel fresh setup. It has default available CreateUsersTable migration file. Go to app/database/create_users_table.php and put the below code here :

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('mobile_number');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password')->nullable();
            $table->rememberToken()->nullable();
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Next migrate the table using the below command :

php artisan migrate

Now go to app/User.php file and add the fillable of mobile_number like this

protected $fillable = [ 'name', 'email', 'mobile_number', ];

Make Route

We will create two routes in web.php file. Go to app/routes/web.php file and create two below routes here :

 Route::get('form', 'FormController@index');
Route::post('save', 'FormController@save');

Create Controller

We need to create a controller name FormController. Use the below command and create Controller :

php artisan make:controller FormController

After successfully create controller go to app/controllers/FormController.php and put the below code :

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator,Redirect,Response;
use App\User;
class FormController extends Controller
{
    public function index()
    {
    
        return view('form');
    }
    public function save(Request $request)
    {
        request()->validate([
        'name' => 'required',
        'email' => 'required|email|unique:users',
        'mobile_number' => 'required|unique:users'
        ]);
        $data = $request->all();
        $check = User::create($data);
        return Redirect::to("form")->withSuccess('Great! Form successfully submit with validation.');
    }
}

Create Blade view

In this step we need to create blade view file. Go to app/resources/views and create one file name form.blade.php .

<!doctype html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>Laravel 5.7 Form Validation Example - Tutsmake.com</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
    <h2 style="margin-top: 10px;">Laravel 5.7 Form Validation Example - Tutsmake.com</h2>
    <br>
    <br>
    @if ($message = Session::get('success'))
    <div class="alert alert-success alert-block">
        <button type="button" class="close" data-dismiss="alert">×</button>
          <strong>{{ $message }}</strong>
    </div>
    <br>
    @endif
  
    <form method="post" action="{{url('post-form')}}">
      @csrf
      <div class="form-group">
        <label for="formGroupExampleInput">Name</label>
        <input type="text" name="name" class="form-control" id="formGroupExampleInput" placeholder="Please enter name">
        <span class="text-danger">{{ $errors->first('name') }}</span>
      </div>
      <div class="form-group">
        <label for="formGroupExampleInput2">Email</label>
        <input type="email" name="email" class="form-control" id="formGroupExampleInput2" placeholder="Please enter email">
        <span class="text-danger">{{ $errors->first('email') }}</span>
      </div>
          
      <div class="form-group">
        <label for="formGroupExampleInput2">Mobile Number</label>
        <input type="text" name="mobile_number" class="form-control" id="formGroupExampleInput2" placeholder="Please enter mobile number">
        <span class="text-danger">{{ $errors->first('mobile_number') }}</span>
      </div>
      <div class="form-group">
       <button type="submit" class="btn btn-success">Submit</button>
      </div>
    </form>
</div>
</body>
</html>

Start Development Server

We need to start development server. Use the php artisan serve command and start your server :

php artisan serve

If you want to run the project diffrent port so use this below command

php artisan serve --port=8080  

Now we are ready to run our example so run bellow command to quick run.

 http://localhost:8000/image
Or direct hit in your browser
http://localhost/FormValidation/public/form

Conclusion

In this tutorial , We have successfully validate form in laravel 5.7 application. We send request to server laravel validation check and return response. our examples run quickly.

Laravel form validation example look like this :

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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