Skip to content

Instantly share code, notes, and snippets.

@arvindsvt
Last active April 14, 2024 16:21
Show Gist options
  • Save arvindsvt/50475782deb6f3ef5956f3ff266e946a to your computer and use it in GitHub Desktop.
Save arvindsvt/50475782deb6f3ef5956f3ff266e946a to your computer and use it in GitHub Desktop.
validate-an-api-request-in-laravel
https://medium.com/@sgandhi132/how-to-validate-an-api-request-in-laravel-35b46470ba88
https://www.youtube.com/watch?v=IvKMPwybSKI
Final code of “LoginRequest.php” file
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Contracts\Validation\Validator;
class LoginRequest extends FormRequest
{
public function rules()
{
return [
'email' => 'required|email|exists:users,email|max:50',
'password'=> 'required',
];
}
public function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json([
'success' => false,
'message' => 'Validation errors',
'data' => $validator->errors()
]));
}
public function messages() //OPTIONAL
{
return [
'email.required' => 'Email is required',
'email.email' => 'Email is not correct'
];
}
}
https://stackoverflow.com/questions/23162617/rest-api-in-laravel-when-validating-the-request
$response = array('response' => '', 'success'=>false);
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
$response['response'] = $validator->messages();
} else {
//process the request
}
return $response;
+++++
$errors = $validation->errors();
return $errors->toJson();
+++++++++++++
There are many ways to get a validator response first is to get an all validation error at the same time i.e you will get a response like below
$validator = \Validator::make($request->all(), [
'username' => 'required|unique:users, username',
'password' => 'required',
]);
if ($validator->fails()) {
$responseArr = CustomHelper::returnRespArr("");
$responseArr['message'] = $validator->errors();;
$responseArr['token'] = '';
return response()->json($responseArr, Response::HTTP_BAD_REQUEST);
}
Response you will get is:
{
"status": false,
"data": [],
"message": {
"username": [
"The username field is required."
],
"password": [
"The password field is required."
]
},
"is_valid": 0,
"token": ""
}
The second way to get a validation response. In this, you will get a one validator error a time.
if ($validator->fails()) {
$responseArr = CustomHelper::returnRespArr("");
$responseArr['message'] = $validator->messages()->first();;
$responseArr['token'] = '';
return response()->json($responseArr,Response::HTTP_BAD_REQUEST);
}
The response you will get
{
"status": false,
"data": [],
"message": "The username field is required.",
"is_valid": 0,
"token": ""
}
https://stackoverflow.com/questions/23162617/rest-api-in-laravel-when-validating-the-reque
https://codehow2.com/laravel/how-to-submit-a-form-using-ajax-in-laravel
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Application;
use Illuminate\Support\Facades\Validator;
class ApplicationController extends Controller
{
public function index(){
$applicants = Application::latest('id')->get();
return view('index', compact('applicants'));
}
public function create(Request $request) {
return view ('application');
}
public function store(Request $request){
$validator = Validator::make($request->all(), ['name' => 'required', 'email' => 'required|email|unique:applications']);
if ($validator->fails()) {
return response()->json([
'error' => $validator->errors()
]);
}
$result = Application::create($request->all());
return response()->json(['success' => 'Form submitted successfully.']);
}
}
<script>
$("#frmAppl").on("submit", function(event) {
event.preventDefault();
var error_ele = document.getElementsByClassName('err-msg');
if (error_ele.length > 0) {
for (var i=error_ele.length-1;i>=0;i--){
error_ele[i].remove();
}
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: "{{ route('application.store') }}",
type: "POST",
data: new FormData(this),
dataType: 'json',
contentType: false,
processData: false,
cache: false,
beforeSend: function() {
$("#submitBtn").prop('disabled', true);
},
success: function(data) {
if (data.success) {
$("#frmAppl")[0].reset();
$("#showMsg").modal('show');
}
else {
$.each(data.error, function(key, value) {
var el = $(document).find('[name="'+key + '"]');
el.after($('<span class= "err-msg">' + value[0] + '</span>'));
});
}
("#submitBtn").prop('disabled', false);
},
error: function (err) {
$("#message").html("Some Error Occurred!")
}
});
});
</script>
@extends('layouts.master')
@section('main-content')
<div class="container">
<div class="col-md-12">
<div class="form-appl">
<div class="title-class">
<h2>Submit Your Application</h2>
</div>
<div class="error" id="message"></div>
<form id="frmAppl" class="frmAppl">
@csrf
<div class="form-group col-md-12 mb-3">
<label for="">Your Name</label>
<input class="form-control" type="text" name="name" id="name" placeholder="Enter Your Name">
</div>
<div class="form-group col-md-12 mb-3">
<label for="">Your Email</label>
<input class="form-control" type="text" name="email" id="email" placeholder="Enter Your Email">
</div>
<div class="form-group col-md-12 mb-5">
<label for="">Address</label>
<textarea class="form-control" name="address" id="address" cols="90" rows="3"
placeholder="Enter Your Address"></textarea>
</div>
<button type="submit" id="submitBtn" class="btn btn-primary">Submit</button>
<a class="btn btn-danger" href="{{route('applications.list')}}">Cancel</a>
</form>
</div>
</div>
</div>
{{-- Modal --}}
<div class="modal fade" tabindex="-1" role="dialog" id="showMsg">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body" style="text-align: center;">
<h4>Thank you for submitting the form</h4>
</div>
<div class="modal-footer" style="border: none;">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
@endsection
@push("js")
<script>
$("#frmAppl").on("submit", function(event) {
event.preventDefault();
var error_ele = document.getElementsByClassName('err-msg');
if (error_ele.length > 0) {
for (var i=error_ele.length-1;i>=0;i--){
error_ele[i].remove();
}
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: "{{ route('application.store') }}",
type: "POST",
data: new FormData(this),
dataType: 'json',
contentType: false,
processData: false,
cache: false,
beforeSend: function() {
$("#submitBtn").prop('disabled', true);
},
success: function(data) {
if (data.success) {
$("#frmAppl")[0].reset();
$("#showMsg").modal('show');
}
else {
$.each(data.error, function(key, value) {
var el = $(document).find('[name="'+key + '"]');
el.after($('<span class= "err-msg">' + value[0] + '</span>'));
});
}
$("#submitBtn").prop('disabled', false);
},
error: function (err) {
$("#message").html("Some Error Occurred!")
}
});
});
</script>
@endpush
https://www.youtube.com/watch?v=e0HLuJ9QK9k
https://github.com/ruhid206/php-ajax-crud-yt
https://webjourney.dev/laravel-9-ajax-form-validation-and-display-error-messages
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment