validate vat number is not working properly - php

I have a form for a user introduce some data, the vat number and country. When the user enter some data and click in "Go to step 2" is made an ajax request to the store() method and here should be be validated the vat number based on the selected country.
But its not working, the "dd($request->country);" shows null. Do you know why?
Html:
<form method="post" id="step1" action="">
...
<div class="form-group font-size-sm">
<select class="form-control" name="country" id="country">
#foreach($countries as $country)
<option value="">{{$country}}</option>
#endforeach
</select>
</div>
<div class="form-group font-size-sm">
<label for="vat"
class="text-gray">VAT</label>
<input type="text" id="vat"
name="vat"
class="form-control" value="">
</div>
...
</form>
// store() method
public function store(Request $request, $id, $slug = null, Validator $validator){
...
$rules = [];
foreach ($request->question_required as $key => $value) {
$rule = 'string|max:255';
if ($value) {
$rule = 'required|' . $rule;
}
$rules["question.{$key}"] = $rule;
}
if ($all) {
$rules["name.*"] = 'required|max:255|string';
}
// the issue is here, country is null
dd($request->country);
dd(substr($request->country, 0, 2) . $request->vat);
//Validator::validate( substr($request->country, 0, 2).$request->vat); // false (checks format + existence)
$validator = Validator::make($request->all(), $rules, $messages);
$errors = $validator->errors();
$errors = json_decode($errors);
if ($validator->fails()) {
return response()->json([
'success' => false,
'errors' => $errors
], 422);
}
return response()->json([
'success' => true,
'message' => 'success'
], 200);
}
// jQuery that do an ajax request

Try passing value into your tag . Php is not getting any value from your input so its showing null

Related

Uploading image from input field and still getting validation error saying that field is required

Route Code:
Route::group(['middleware' => 'auth', 'prefix' => 'admin'], function(){
Route::resource('gallery', GalleryController::class);
});
The Form I'm Using to Upload the File:
<form action="{{ route('gallery.store') }}" method="post" enctype="multipart/form-data">
#csrf
<div class="input-group mb-3">
<div class="custom-file">
<input type="file" class="custom-file-input" name="gallery_img" id="inputGroupFile01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
#error('gal_img')
<span class="text-danger">{{ $message }}</span>
#enderror
<div class="input-group-append">
<div class="col-sm-10" style="padding-left: 1px;">
<button type="submit" class="btn btn-dark">Save</button>
</div>
</div>
Controller Code:
public function store(GalleryRequests $request)
{
$gal_img = $request->file('gallery_img');
$gal_file = date('YmdHi').$gal_img->getClientOriginalName();
$gal_img->move(public_path('upload/gallery'), $gal_file);
$save_path = 'upload/gallery/'.$gal_file;
Gallery::insert([
'gal_img' => $save_path
]);
$notification = array(
'message' => 'Slider Inserted Successfully',
'alert-type' => 'success'
);
return redirect()->back()->with($notification);
}
Request file validation:
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'gal_img' => 'required'
];
}
public function messages(){
return [
'gal_img.required' => 'Please Select an Image First',
];
}
The error I get when trying to save after selecting an Image:
Trying to figure out what I've done wrong for hours and am so frustrated right now, please help me to resolve this issue.
Thanks in advance.
Field in form is named gallery_img so that name has to be checked:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'gallery_img' => 'required'
];
}
public function messages()
{
return [
'gallery_img.required' => 'Please Select an Image First',
];
}

How do I redirect to another page after form submission in Laravel

form
When i submit the form it redirects back to the form itself, can anyone help me?
<form action="/jisajili" method="POST">
#csrf
<div class="card-panel z-depth-5">
<h5 class="center red-text">Jiunge Nasi</h5>
<div class="input-field">
<i class="material-icons prefix">account_circle</i>
<input type="text" name="username" class="validate">
<label>Jina lako</label>
</div>
<div class="input-field">
<i class="material-icons prefix">phone</i>
<input type="number" name="phone" class="validate">
<label>Nambari ya simu</label>
</div>
....
</p>
<input type="submit" name="submit" value="Jiunge" class="btn left col s12 red">
Controller
class registration extends Controller{
public function create(){
return view('jisajili.jiunge');
}
public function store(Request $request){
$reg = new regist;
$reg->jina = $request->input('username');
$reg->simuNumber = $request->input('phone');
$reg->email = $request-> input('email');
$reg -> password = bcrypt($request->input('password'));
$cpassword = $request -> input('cpassword');
$reg->save();
$validated = $request->validate([
'name' => 'required|unique:posts|max:10',
'body' => 'required',
]);
return redirect('home');
}
}
What I would do is first check for the data requirements before you add the object to the database. Also I would add the columns of the models into the Model file to use the Object::create function with an array parameter.
I recomment to use routing in your blade file. I noticed you used action="/route". What you want to do is naming your routes with ->name('route_name') in the route files. To use them in your blade files with the global route function route="{{ route('route_name') }}".
<?php
class PostController extends Controller
{
public function index()
{
return view('post.create');
}
public function store(\Illuminate\Http\Request $request)
{
$validator = Validator::make(
$request->all(),
[
'name' => 'required|unique:posts|max:10',
'body' => 'required'
]
);
// Go back with errors when errors found
if ($validator->fails()) {
redirect()->back()->with($validator);
}
Post::create(
[
'name' => $request->get('name'),
'body' => $request->get('body')
]
);
return redirect()
->to(route('home'))
->with('message', 'The post has been added successfully!');
}
}
What you can do after this is adding custom errors into the controller or add them into your blade file. You can find more about this in the documentation of Laravel.
it redirects you back because of validation error.
change password confirmation name from cpassword into password_confirmation as mentioned in laravel docs
https://laravel.com/docs/7.x/validation#rule-confirmed
update your controller into:
public function store(Request $request){
$validated = $request->validate([
'username' => 'required',
'phone' => 'required',
'email' => 'required',
'password' => 'required|confirmed'
]);
$reg = new regist;
$reg->jina = $request->input('username');
$reg->simuNumber = $request->input('phone');
$reg->email = $request-> input('email');
$reg -> password = bcrypt($request->input('password'));
$reg->save();
return redirect('home');
}
in your blade add the following to display validation errors:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

Make validate to be Only integer input in laravel

I need to make validate the (request_number) input is the Only integer and show a Message if the student writes a string as an example.
the Message if the user write the existing number is (the number of your order exists)
and the message if the user writes the non-integer value is (the input should be the Only Number)
Now I want to make double validation on (request_number).
this is my store in my controller
public function store(Request $request)
{
$excuse = new Student();
$excuse->request_number = $request->input('request_number');
$validatedData = $request->validate([
'request_number' => Rule::unique('students')->where(function ($query)
{
return $query->whereIn('status_id',[2,4,6,5]);
})]);
$excuse->student_id = Auth::guard('web')->user()->id;
$excuse->status_id = 1;
$excuse->college_id = Auth::guard('web')->user()->college_id;
$excuse->save();
return redirect('/students');
}
and this is my form to make a request
<form method="post" action="{{url('/student')}}" enctype="multipart/form-data">
#csrf
<h1> Make order FORM</h1>
<div class="form-group">
<label for="requestnumber"> write the Request Number </label><br>
<input type="text" id="request_number" name="request_number"class="form-control" minlength="5" style="width:50%" required >
</div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li> the number of request is exists </li>
#endforeach
</ul>
</div>
#endif
<br>
<button type="submit" class="btn btn-primary">send</button><br>
</form>
Try replacing your code with this
$status = Student ::whereIn('status_id', [2,3,4,5])->pluck
('status_id') ;
$validatedData = $request->validate([
'request_number ' =>
'required|integer ',
Rule::unique('students')->where(function ($query)
use ($status) {
return $query->whereIn('status_id', $status);
})
]) ;
and let me know either it is the thing you want or not
$validatedData = $request->validate([
'request_number ' => [
'required', 'integer', function($attr, $val, $fail) {
if (YourTargetModel::where('id', [1,2,3])->count() > 0) {
return $fail("The request number field should be
unique");
}
}]
]);
You can have many rules for a single field by using an array of rules:
'request_number' => [
'integer',
Rule::unique('students')->where(function ($query) {
return $query->whereIn('status_id', [2, 4, 6, 5]);
}),
]

Form submission returns inputs Laravel

I'm trying to create a submission form, if a user submit the form it should redirect him to the next page which is in confirmation controller. So far it redirects back with the inputs like this
{"shipping_city":"gfg","shipping_phone":"087484","shipping_name":"Hellle",}
Here is my code
CheckoutController
public function store(Request $request)
{
foreach(session('cart') as $productId =>$item);
$product = product::find($productId);
//Insert into orders table
$order = Order::create([
'shipping_city' => $request->city,
'shipping_phone' => $request->phone,
'shipping_name' => $request->name,
]);
if ($order) {
foreach(session('cart') as $productId =>$item) {
if (empty($item)) {
continue;
}
$product = product::find($productId);
OrderProduct::create([
'order_id' => $order->id ?? null,
'product_id' => $productId,
'quantity' => $item['quantity'],
]);
}
return $order;
}
$cart = session()->remove('cart');
return redirect()->route('confirmation.index');
}
Checkout.blade
<form action="{{ route('checkout.store') }}" method="POST" id="payment-form">
{{ csrf_field() }}
<div class=shippingform>
<div class="form-group">
</div>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" value="{{ auth()->user()->name }}" required>
</div>
<div class="half-form">
<div class="form-group">
<label for="city">City</label>
<input type="text" class="form-control" id="city" name="city" value="{{ old('city') }}" required>
</div>
</div> <!-- end half-form -->
<div class="form-group">
<label for="phone">Phone</label>
<input type="text" class="form-control" id="phone" name="phone" value="{{ old('phone') }}" required>
</div>
<div class="spacer"></div>
<div class="spacer"></div>
<button type="submit" id="complete-order" class="buttons-primary full-width">Complete Order</button>
</form>
ConfirmationController
public function index()
{
{
if (! session()->has('success_message')) {
return redirect('/');
}
return view('thankyou');
}
}
Routes
Route::post('/checkout', 'CheckoutController#store')->name('checkout.store');
Any help will be appreciated.
Let's take a look at what your code currently does and what you want it to do:
Current Code with comments:
public function store(Request $request) {
foreach(session('cart') as $productId =>$item);
$product = product::find($productId);
//Insert into orders table
$order = Order::create([
'shipping_city' => $request->city,
'shipping_phone' => $request->phone,
'shipping_name' => $request->name,
]);
if ($order) { // If a new order was successfully created
foreach(session('cart') as $productId =>$item) {
// Do some stuff with each item / product
}
return $order; // return the newly created order with it's data
}
// If we didn't created a new order for whatever reason
$cart = session()->remove('cart');
return redirect()->route('confirmation.index'); // Redirect user to the "confirmation.index" route
}
As you can see, you just return the data of the created order (when $order is not false), otherwise you redirect to the "confirmation.index" page. Since this always does the opposite of what it should do (returning the order although you should be redirected to the confirmation page and vice versa), you have to swap the cases:
public function store(Request $request) {
...
if ($order) { // If a new order was successfully created
foreach(session('cart') as $productId =>$item) {
// Do some stuff with each item / product
}
$cart = session()->remove('cart');
return redirect()->route('confirmation.index'); // Redirect user to the "confirmation.index" route
}
// If we didn't created a new order for whatever reason
return false; // return something else, since we didn't create an order
}

Displaying laravel error messages on redirect

I have a form which i am hoping to use to insert some data to mysql. I have setup the validator like this
public function insert_post(){
$rules = array(
'model' => 'required',
'country' => 'required',
'engine' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
// get the error messages from the validator
$messages = $validator->messages();
echo '<pre>';
print_r($messages);
echo '</pre>';
return Redirect::to('create-posts')
->withErrors($validator);
}
else {
$i = new Text;
$i->model = request('model');
$i->country = request('country');
$i->engine = request('engine');
$i->save();
return redirect('/');
}
}
My create-posts route looks like this.
public function create_post(){
return view('create-posts');
}
However, its not displaying the error since i think i am loading a fresh create-posts and the validator messages are lost.
view code
<div class="form-group">
<label for="inputEmail" class="control-label col-xs-2">Model</label>
<div class="col-xs-10">
<input type="text" class="form-control" id="inputEmail" name="model" placeholder="Model">
#if ($errors->has('model')) <p class="help-block">{{ $errors->first('model') }}</p> #endif
</div>
</div>
Is that what's the cause?.
In case you want to return to the last view, you can use:
return Redirect::back()->withErrors($validator);
Instead of return Redirect::to('create-posts')->withErrors($validator);.

Categories