Laravel Validate Object
Hello, friends today we learn how to write a code for laravel array validation. i have to tell you something that is I read lots of documents but I did not understand this concept before nowadays i am very clear about this concept, so i am trying to explain you here by an example so you can use also and easily understand. :)
Laravel array validation helps us to validate the array of objects coming from the frontend side when any type of form submission is applied so we can get the request first then we should validate object like i can give you one example - if you have multiple form submissions with multiple fields so we need to validate all fields data so we can store validate data into our database
i know i am using validate multiple times so let me tell you about validating means i am trying to tell you that if there is a phone number field then we have to valid phone number before storing data into the database correct? i hope now you understand my concept more.
Step:1 install laravel using below command
Step:2 Configure database setup using .env file in root folder
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_array_object_validation
DB_USERNAME=root
DB_PASSWORD=root@123
Note:- make sure - you are using your database name and username password of your PHP MySQL
Step:3 Create table, model, controller and migration using single below one command
php artisan make:model Customer -mc
Step:4 Now check one migration file generated in the database/migrations modify like below code
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCustomersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('customers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('email')->unique()->nullable();
$table->string('name')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('customers');
}
}
Step:5 Now check one another App/Models that folder generate model Customer.php file using step-3 command and modify that also
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
use HasFactory;
protected $fillable = ['name', 'email', 'created_at', 'updated_at'];
}
Step:6 Now check one another App/Http/Controllers that folder generate model CustomerController.php file using step-3 command and modify that also
<?php
namespace App\Http\Controllers;
use App\Models\Customer;
use Illuminate\Http\Request;
use Session;
class CustomerController extends Controller
{
public function index()
{
return view('customers.list');
}
public function store(Request $request)
{
$rules = [
"customers.*.email" => ["required", "email", "unique:users"],
"customers.*.name" => ["required", "min:6"],
];
$message = [
"customers.*.email.required" => "The Email field is required.",
"customers.*.email.unique" => "The Email field must be unique.",
"customers.*.name.required" => "The Name field is required.",
"customers.*.name.min" => "The Name field required minimum 6 character.",
];
$validated = $request->validate($rules, $message);
$data = [];
foreach ($validated['customers'] as $key => $value) {
$data[$key]['email'] = $value['email'];
$data[$key]['name'] = $value['name'];
$data[$key]['created_at'] = now();
}
Customer::query()->insert($data);
return back()->with('success', 'User created successfully.');
}
}
Step:7 Create route (router/web.php)
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CustomerController;
/*
|--------------------------------------------------------------------------
| 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::resource('customers', CustomerController::class);
Step:8 Create Blade file into resources/views/customers/create.blade.php
@extends('layouts.front')
@section('content')
<div class="container py-5 my-5 m-auto justify-center">
<h1 class="text-center">MTITsolution - Laravel Array Validation</h1>
<div class="row border border-1 p-5">
<div class="col">
@if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
@php
Session::forget('success');
@endphp
</div>
@endif
</div>
<form class="row g-3" method="post" action="{{route('customers.store')}}">
@csrf
@for($i = 0;$i < 5;$i++)
<div class="row">
<div class="col-md-6">
<label for="inputEmail{{$i}}" class="form-label">Email</label>
<input name="customers[{{$i}}][email]" type="text" class="form-control"
id="inputEmail{{$i}}">
@if($errors->any())
<p class="text-danger">
@if ($errors->has('customers.'.$i.'.email'))
{{ $errors->first('customers.'.$i.'.email') }}
@endif
</p>
@endif
</div>
<div class="col-md-6">
<label for="inputName{{$i}}" class="form-label">Name</label>
<input name="customers[{{$i}}][name]" type="text" class="form-control"
id="inputName{{$i}}">
@if($errors->any())
<p class="text-danger">
@if ($errors->has('customers.'.$i.'.name'))
{{ $errors->first('customers.'.$i.'.name') }}
@endif
</p>
@endif
</div>
</div>
@endfor
<div class="col-12">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
@endsection
إرسال تعليق