How to Validate Form in Laravel 11 Example

Hello developer, in this article we'll see how to validate forms in laravel 11. Form validation is a crucial aspect of web development, ensuring that the data entered by users meets the specified criteria before it's processed further.

Laravel 11, from setting up validation rules to displaying error messages and handling the validation logic in our controllers.

So, let's see Laravel 11 form validation and laravel 11 validation.

Step 1: Install Laravel 11

In this step, we'll install the laravel 11 application using the following composer command.

composer create-project laravel/laravel laravel-1-form-validation

 

Step 2: Create Controller

Now, we'll create a UserController.php file using the following artisan command. and we'll validate inputs in the store() function.

php artisan make:controller UserController

app/Http/Controllers/UserController.php

<?php
      
namespace App\Http\Controllers;
      
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
     
class UserController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(): View
    {
        return view('create');
    }
          
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request): RedirectResponse
    {
        $validatedData = $request->validate([
                'name' => 'required',
                'password' => 'required|min:5',
                'email' => 'required|email|unique:users'
            ], [
                'name.required' => 'Name field is required.',
                'password.required' => 'Password field is required.',
                'email.required' => 'Email field is required.',
                'email.email' => 'Email field must be email address.'
            ]);
        
        $validatedData['password'] = bcrypt($validatedData['password']);
        $user = User::create($validatedData);
              
        return back()->with('success', 'User created successfully.');
    }
}
 
Step 3: Create Routes

Then, we'll define routes on the web.php file.  So, add the following code to this file.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\UserController;
  
Route::get('users/create', [ UserController::class, 'create' ]);
Route::post('users/create', [ UserController::class, 'store' ])->name('users.store');
 
Step 4: Create Blade File

In this step, we'll create a blade file and add a simple form for validation in laravel 11. So, add the following code to this file.

resources/views/create.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How to Validate Form in Laravel 11 Example - Techsolutionstuff</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
</head>
<body>
<div class="container">
  
    <div class="card mt-5">
        <h3 class="card-header p-3"><i class="fa fa-star"></i> How to Validate Form in Laravel 11 Example - Techsolutionstuff</h3>
        <div class="card-body">
            @session('success')
                <div class="alert alert-success" role="alert"> 
                    {{ $value }}
                </div>
            @endsession
          
            <!-- Way 1: Display All Error Messages -->
            @if ($errors->any())
                <div class="alert alert-danger">
                    <strong>Whoops!</strong> There were some problems with your input.<br><br>
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
             
            <form method="POST" action="{{ route('users.store') }}">
            
                {{ csrf_field() }}
            
                <div class="mb-3">
                    <label class="form-label" for="name">Name:</label>
                    <input 
                        type="text" 
                        name="name" 
                        id="name"
                        class="form-control @error('name') is-invalid @enderror" 
                        placeholder="Name">
      
                    <!-- Way 2: Display Error Message -->
                    @error('name')
                        <span class="text-danger">{{ $message }}</span>
                    @enderror
                </div>
           
                <div class="mb-3">
                    <label class="form-label" for="password">Password:</label>
                    <input 
                        type="password" 
                        name="password" 
                        id="password"
                        class="form-control @error('password') is-invalid @enderror" 
                        placeholder="Password">
      
                    <!-- Way 3: Display Error Message -->
                    @if ($errors->has('password'))
                        <span class="text-danger">{{ $errors->first('password') }}</span>
                    @endif
                </div>
             
                <div class="mb-3">
                    <label class="form-label" for="email">Email:</label>
                    <input 
                        type="text" 
                        name="email" 
                        id="email"
                        class="form-control @error('email') is-invalid @enderror" 
                        placeholder="Email">
      
                    @error('email')
                        <span class="text-danger">{{ $message }}</span>
                    @endif
                </div>
           
                <div class="mb-3">
                    <button class="btn btn-success btn-submit"><i class="fa fa-save"></i> Submit</button>
                </div>
            </form>
        </div>
    </div>       
          
</div>
</body>
</html>
 
Step 5: Run the Laravel 11 Application

Now, run the laravel 11 application using the following command.

php artisan serve

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS