Laravel 8.x Form Validation with Custom Error Messages

Hi Artisan

In this tutorial i will explain about laravel 8 form validation example. We will see from scratch laravel 8 form validation custom error messages step by step.

In this tutorial i wil show you how to validate a html form data and save it into database in laravel 8. You can also define custom error messages in laravel 8 form validation.

we will display error message with each field. we will use has() for checking is error message in laravel 8. Here, i am going to show you very simple example of form validation so, you can simply use in your laravel 8 project.

Read this docs to learn more about validation in laravel 6

 

Read also : Basic Usage of Cache in Laravel

 

laravel-6-form-validation-with-error-message

Step 1 : Create Route

Here we are learning easy example of form validation in laravel 6. Open your routes/web.php and paste this following code.

routes/web.php

Route::get('storeuser', 'HomeController@create')->name('storeuser');
Route::post('storeuser', 'HomeController@store');

 

Step 2 : Create Controller:

Now we will add two controller method, one will just display blade file with get request, and another for post request, i write validation for that, so simply add both following method on it.

app/Http/Controllers/HomeController.php

namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\User;
  
class HomeController extends Controller
{
    public function create()
    {
        return view('createUser');
    }
  
    public function store(Request $request)
    {
        $request->validate(
            [
                'name' => 'required',
                'password' => 'required|min:5',
                'email' => 'required|email|unique:users'
            ], 
            [
                'name.required' => 'Name is required',
                'password.required' => 'Password is required'
            ]
          );
   
        $input = $request->all();
        $input['password'] = bcrypt($input['password']);
        $user = User::create($input);
    
        return back()->with('success', 'User created successfully.');
    }
}

 

Step 3 : Create Blade File

now here we will create createUser.blade.php file and here we will create bootstrap simple form with error validation message. So, let's create following file:

resources/views/createUser.blade.php

 

Read also : Send Notification to Inactive User with Task Scheduling in Laravel using Custom Command

 

 

Now you can check it. Hope it can help you.

 

author-image
Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js