Laravel Validation

version : Laravel 10
Post Time : 21-05-2024

Laravel Validation

install laravel
         - composer create-project --prefer-dist laravel/laravel:^10.0 laravel_demo

Create ValidationDemoController Controller  :
           - php artisan make:controller ValidationDemoController

app/Http/Controllers/ValidationDemoController.php

                                      
                                        

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class ValidationDemoController extends Controller
{
   public function index(Request $request)
   {
       return view('validation_demo');
   }

   public function saveUserData(Request $request)
   {
       $messages = [
           'name.required' => 'The name field is required.',
           'email.required' => 'The email field is required.',
           'email.email' => 'The email must be a valid email address.',
           'password.required' => 'The password field is required.',
           'password.min' => 'The password must be at least 8 characters.',
       ];
      $validatedData = $request->validate([
           'name' => 'required|max:255',
           'email' => 'required|email|unique:customers',
           'password' => 'required|min:8',
       ], $messages);
       $data_array = [
           'name' => $request->input('name'),
           'email' => $request->input('email'), 
           'password' => $request->input('password'), 
           'created_at' => date('Y-m-d H:i:s'), 
       ];
       $save_flag = DB::table('customers')->insert($data_array);
       if($save_flag == true)
           return redirect()->route('validation_demo')->with('success', 'Successfully Saved...!!');
       else
           return redirect()->route('validation_demo')->with('error', 'Something went wrong...!!');
   }
}

Carete validation_demo blade file :-
Resources/views/validation_demo.blade.php

                                      
                                        

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
       <!-- Bootstrap CSS -->
   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> 
   <style>
       .error{
           color:red;
       }
       .basic-form{
           display:flex;
           justify-content:center;
       }
   </style>
</head>
<body>
   <div class="mb-3 row text-center">
       <h1>USER INFO</h1>
   </div>
   <div class="row basic-form">
       <div class="col-md-6">
           <form class="dz-form pb-3" action="{{ route('saveUserData') }}" method="POST" name="login_form" id="login_form">
               @csrf
               @if(Session::has('error'))
                   <div class="alert alert-danger" id="success-alert">
                       {{Session::get('error')}}
                   </div>
               @endif
               @if(Session::has('success'))
                   <div class="alert alert-success" id="success-alert">
                       {{Session::get('success')}}
                   </div>
               @endif
               <h3 class="form-title m-t0">Personal Information</h3>
               <div class="dz-separator-outer m-b5">
                   <div class="dz-separator bg-primary style-liner"></div>
               </div>
               <div class="form-group mb-3">
                   <input type="text" class="form-control" placeholder="Name" name="name" value="{{ old('name') }}">
                   @error('name')
                       <label class="error">{{ $message }}</label>
                   @enderror
               </div>
               <div class="form-group mb-3">
                   <input type="email" class="form-control" placeholder="Email" name="email" value="{{ old('email') }}">
                   @error('email')
                       <label class="error">{{ $message }}</label>
                   @enderror
               </div>
               <div class="form-group mb-3">
                   <input type="password" class="form-control" placeholder="Password" name="password" id="password" value="">
                   @error('password')
                       <label class="error">{{ $message }}</label>
                   @enderror
               </div>
               <div class="form-group text-center mb-5 forget-main">
                   <button type="submit" class="btn btn-primary">Save</button>
               </div>
           </form>
       </div>
   </div>
</body>
</html>

routes/web.php

                                      
                                        

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ValidationDemoController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
   return view('welcome');
});

Route::get('/validation_demo', [ValidationDemoController::class,'index'])->name('validation_demo'); 
Route::post('/saveUserData', [ValidationDemoController::class, 'saveUserData'])->name('saveUserData');

Using Validator Method :- 

                                      
                                        

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use Illuminate\Support\Facades\Validator;

class ValidationDemoController extends Controller
{
   public function index(Request $request)
   {
       return view('validation_demo');
   }
   /*------------------Using Validator Method------------*/
   public function saveUserData(Request $request)
   {
       $validator = Validator::make($request->all(), [
           'name' => 'required|max:255',
           'email' => 'required|email|unique:customers',
           'password' => 'required|min:8',
       ]);
       if ($validator->fails()) {
           return redirect()->route('validation_demo')->withErrors($validator)->withInput();
       }
       $data_array = [
           'name' => $request->input('name'),
           'email' => $request->input('email'), 
           'password' => $request->input('password'), 
           'created_at' => date('Y-m-d H:i:s'), 
       ];
       $save_flag = DB::table('customers')->insert($data_array);
       if($save_flag == true)
           return redirect()->route('validation_demo')->with('success', 'Successfully Saved...!!');
       else
           return redirect()->route('validation_demo')->with('error', 'Something went wrong...!!');
   }
}

Using Sometimes :-

                                      
                                        

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use Illuminate\Support\Facades\Validator;

class ValidationDemoController extends Controller
{
   public function index(Request $request)
   {
       return view('validation_demo');
   }
   /*---------Using sometimes Method-------*/
   public function saveUserData(Request $request)
   {
       $validator = Validator::make($request->all(), [
           'name' => 'required|max:255',
           'email' => 'required|email|unique:customers',
       ]);
       /*--------------Required password length 8 when email insert test@example.com ------*/
       $validator->sometimes('password', 'required|min:8', function ($input) {
           return $input->email == 'test@example.com';
       });
       if ($validator->fails()) {
            return redirect()->route('validation_demo')->withErrors($validator)->withInput();
       }
       $data_array = [
           'name' => $request->input('name'),
           'email' => $request->input('email'), 
           'password' => $request->input('password'), 
           'created_at' => date('Y-m-d H:i:s'), 
       ];
       $save_flag = DB::table('customers')->insert($data_array);
       if($save_flag == true)
           return redirect()->route('validation_demo')->with('success', 'Successfully Saved...!!');
       else
           return redirect()->route('validation_demo')->with('error', 'Something went wrong...!!');
   }
}

Using Inline :-

                                      
                                        

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class ValidationDemoController extends Controller
{
   public function index(Request $request)
   {
       return view('validation_demo');
   }
   /*-------------Using Inline Method----------*/
   public function saveUserData(Request $request)
   {
       $validatedData = $request->validate([
           'name' => 'required|max:255',
           'email' => 'required|email|unique:customers',
           /*---Required password length 8 when email insert test@example.com ---*/
           'password' => $request->email == 'test@example.com' ? 'required|min:8' : '',
       ]);
       $data_array = [
           'name' => $request->input('name'),
           'email' => $request->input('email'), 
           'password' => $request->input('password'), 
           'created_at' => date('Y-m-d H:i:s'), 
       ];
       $save_flag = DB::table('customers')->insert($data_array);
       if($save_flag == true)
           return redirect()->route('validation_demo')->with('success', 'Successfully Saved...!!');
       else
           return redirect()->route('validation_demo')->with('error', 'Something went wrong...!!');
   }
}