How to create form validation in Laravel 8

How to create form validation in Laravel 8

Posted by Ervin Adams on May 25, 2021

How to create form validation in Laravel 8

How to create form validation in Laravel 8

Posted by Ervin Adams on May 25, 2021

In this tutorial you will have an understanding of how to validate your incoming data using Laravel 8. In this scenario we will create a "book" class and receive data "title" and "author" in order to store book records. Before you start ensure that you have a live database connection. Go to this link https://wecode101.com/xampp_development_environment_for_laravel if you want to learn how to set up Laravel on your PC.

Step 1. Create migration for books table

php artisan make:migration create_books_table

Go to "database/migrations" and edit create_books_table.php file 

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class CreateBooksTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up() {

   Schema::create('users', function (Blueprint $table) {

   $table->id();

   $table->string('title');

   $table->string('author');

   $table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

   Schema::dropIfExists('books');

}

}

Step 2. Execute command to create table in databse

php artisan migrate

Step 3. Create a book model

php artisan make:model Book

Go to "app/models" and edit Book model

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

class Book extends Model

{

use HasFactory;

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = ['title','author'];

}

Step 4. Create a book controller 

php artisan make:controller BookController

"app/Http/Controller/BookController"

namespace App\Http\Controllers;

use App\Models\Book;

use Illuminate\Contracts\Foundation\Application;

use Illuminate\Http\RedirectResponse;

use Illuminate\Http\Request;

use Illuminate\Http\Response;

use Illuminate\Routing\Redirector;

use Illuminate\View\View;

class BookController extends Controller

{

/**

* Show the form to store book record.

*

* @return View

*/

public function create(): View

{

   return view('create');

}

/**

* Store a new book record.

*

* @param Request $request

* @return Application|Redirector|RedirectResponse

*/

public function store(Request $request)

{

$request->validate([

   'title' => 'required|unique:books|max:100',

   'author' => 'required',

]);

   $title = $request->input('title');

   $author = $request->input('author');

   Book::create(['title' => $title, 'author' => $author]);

   return redirect('/');

}

}

Step 5. Add routes Go to "auth/web.php" and edit

use App\Http\Controllers\BookController;

use Illuminate\Support\Facades\Route;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!

|

*/

Route::get('/', [BookController::class, 'create'])->name('create.book');

Route::post('/book', [BookController::class, 'store'])->name('store');

Step 6. Create view "create.blade.php"

place this file in "resources/views"

<!DOCTYPE html>

      <head>    

             <meta charset="utf-8">    

             <title>Wecode101 validation tutorial</title>    

             <meta name="description" content="Wecode101 validation in Laravel 8">    

             <meta name="author" content="Wecode101">    

             <meta name="csrf-token" content="{{ csrf_token() }}">  

              <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"                      integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"                         crossorigin="anonymous">

        </head>

<html>

          <body>

                 <div class="container align-items-start">  

                 <h3 class="d-flex justify-content-center">Store Book Records</h3>    

                  @if ($errors->any())        

                 <div class="alert alert-danger">        

                  <ul>                

                  @foreach ($errors->all() as $error)      

                         <li>{{ $error }}</li>                

                    @endforeach            

                     </ul>      

            </div>    

         @endif  

            <div class="container-fluid d-flex justify-content-center mt-4" style="max-width: 30em">  

             <form id="signin" class="form-horizontal validate-form" method="POST" action="{{ route('store') }}">                         {{ csrf_field() }}          

              <div class="form-group">            

              <label for="title" class="control-label">Title</label>        

              <input id="title" type="text" class="form-control" name="title" value="{{ old('title') }}">        

              </div>        

              <div class="form-group">  

                      <label for="author" class="control-label">Author</label>      

                      <input id="author" type="text" class="form-control" name="author" value="{{ old('author') }}"        

                </div>          

               <div class="form-group mb-0">    

                       <button type="submit" class="btn btn-primary">submit</button>

                </div>    

             </form>

        </div>

       </div>

</body>

</html>

Step 7. Start server

php artisan serve

Go to the web browser. If all went well you should see the form. Click the submit button without filling in the input fields and you should see validation in action.

If you wish to download this tutorial go to https://github.com/wecode101/laravel_validation