Laravel / Vue: Validating when using v-model - laravel

I am using Laravel and Vue js, and I can not figure out how to validate this field using Laravel.
Vue-component:
<div v-for="problem in problems">
<div>
<label :for="problem.id">{{problem.title}}</label>
<input type="text" class="form-control" :id="problem.id"
v-model="problem.rating">
</div>
</div>
This returns an array
array:2 [
"problems" => array:2 [
0 => array:2 [
"id" => 33
"rating" => "12"
]
1 => array:2 [
"id" => 38
"rating" => "3"
]
]
]
Now I do not know how to validate this using Laravels validation. I have tried a lot of things like
$this->validate($request, [
'rating' => 'required|integer',
]);
But this does of course not work here. Can anyone please help me?
EDIT:
I figured it out. Needed to use
$this->validate($request, [
'problems.*.rating' => 'required|integer',
]);

Related

Laravel validate multidimensional array on dynamic fields

I am creating a dynamic form and hence inputs names are being created dynamically, But validation is not working properly.
Input Example:
<input type="text" id="information" name="page[home][Admin]user[]">
<input type="text" name="action[home][Admin]user[]">
Validation:
$validatedData = $request->validate([
'page'=>'required|array',
'page.*.user'=>'required',
]);
But it's not working
try changing input name to
<input type="text" id="information" name="page[home][Admin][user][]">
and validation rules like
[
'page'=>'required|array',
'page.*.*.user.*'=>'required',
]
So Request contain page data like
"page" => array:1 [▼
"home" => array:1 [▼
"Admin" => array:1 [▼
"user" => array:2 [▼
0 => ""
]
]
]
]

Laravel not creating response custom header

When request is json all ok I got my 'xxx' header, but when it's direct request to page - my header does't exists in response.
I tried any variation of response()->header, response('content',200,['xxx'=>'xxx']) and no success
My code in controller:
return $request->wantsJson()
? response([
'html' => view('components.tarif-list', compact('tarifs'))->render(),
'pagination' => $tarifs->appends(request()->query())->links()->toHtml(),
'head' => $seo_block,
'stats' => $stats
])->header('xxx','xxx')
: response(view('home',compact('tarifs','seo_block'))->render())->header('xxx','xxx');
home.blade.php
#extends('layouts.main')
#section('content')
<x-filters/>
<div id="head" class="alert alert-success" role="alert">
#if(!empty($seo_block))
{!! $seo_block !!}
#elseif($tarifs->isEmpty())
empty
#else
hello
#endif
</div>
{{$tarifs->appends(request()->query())->links()}}
<table id="tarif-list" class="table table-hover table-striped">
<x-tarif-list :tarifs="$tarifs"/>
</table>
{{$tarifs->appends(request()->query())->links()}}
#endsection
If you dd this line of code
response(view('home',compact('tarifs','seo_block'))->render())->header('xxx','xxx')
You will see this response
Symfony\Component\HttpFoundation\ResponseHeaderBag {#2878
#computedCacheControl: array:2 [
"no-cache" => true
"private" => true
]
#cookies: []
#headerNames: array:3 [
"cache-control" => "Cache-Control"
"date" => "Date"
"xxx" => "xxx"
]
#headers: array:3 [
"cache-control" => array:1 [
0 => "no-cache, private"
]
"date" => array:1 [
0 => "Thu, 07 May 2020 11:27:31 GMT"
]
"xxx" => array:1 [
0 => "xxx"
]
]
#cacheControl: []
}
So the keys are there, But how you retrieving the headers in your blade file?
the problem was in controller before response was dump() and as we know headers must be first content at page.
But why php or laravel does't tell about it.
Default php warning for it:
PHP Warning: Cannot modify header information - headers already sent by..........

customize error message for mimes not working

I can not customize the error message for mimes
I try the solution given here laravel 5.4 custom error message for MIME not working? but without success
Request :
public function rules()
{
$rules = [
'album'=> 'required',
'add_image.*' => 'image|mimes:png|max:2000',
];
return $rules;
}
public function messages()
{
$messages = [
'album.required' => 'Album is required',
'add_image.mimes' => "Image isn't png",
];
return $messages;
}
Form view :
<form class="addImage" method="post" action="{{route('addImage.form')}}" enctype="multipart/form-data">
{{csrf_field()}}
<select name="album">
<option value="">-----</option>
#foreach($albums as $album)
<option value="{{$album}}">{{$album}}</option>
#endforeach
</select>
<input multiple="multiple" name="add_image[]" type="file" />
<button class="buttonADM" type="submit">Send</button>
</form>
Thanks for your help and sorry for my bad english
You are validating an array, so try this instead:
'add_image.*.mimes' => "Image isn't png",
I used your form on my project, and tried this:
$valid = Validator::make(request()->all(), [
'add_image.*' => 'image|mimes:png'
], [
'add_image.*.mimes' => 'Image isnt png'
]);
dd($valid->errors());
// output
{
"add_image.0": [
"Image isnt png"
],
"add_image.1": [
"Image isnt png"
],
"add_image.2": [
"Image isnt png"
]
}
and I got the custom message. So please check your error bag if it contains the correct messages, and make sure that you print it okay.
i have not same result
Controller
public function addImage(/*addImageRequest $request*/){
if(session('user')['isA'] == 1){
$valid = Validator::make(request()->all(), [
'add_image.*' => 'image|mimes:png'
], [
'add_image.*.mimes' => 'Image isnt png'
]);
dd($valid->errors());
}
}
Return :
MessageBag {#224 ▼
#messages: array:1 [▼
"add_image.0" => array:1 [▼
0 => "The add_image.0 failed to upload."
]
]
#format: ":message"
}

Laravel old() function not working --- flash dose not work (stoped working!!)

I'm trying to use old() in Laravel but it doesn't work.
In my controller:
dd(back()->withInput());
this is the session result
#session: Store {#364 ▼
#id: "dyNmtFJVQCQmcCob4SPYEBzWHJ6TJeM9X0mzWWu7"
#name: "laravel_session"
#attributes: array:6 [▼
"_token" => "NVJATvxuHRlGbAC1jUEIjS6gbLQQEWPIIV41fLYd"
"url" => []
"_previous" => array:1 [▼
"url" => "http://localhost:8000/units/23/rents/create"
]
"_flash" => array:2 [▼
"old" => []
"new" => array:1 [▼
0 => "_old_input"
]
]
"login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d" => 1
"_old_input" => array:5 [▼
"_token" => "NVJATvxuHRlGbAC1jUEIjS6gbLQQEWPIIV41fLYd"
"contract_id" => "20"
"unit_id" => "23"
"amount_paid" => "1"
"submit" => "submit"
]
]
#handler: FileSessionHandler {#363 ▶}
#started: true
value="{{ old('amount_paid')}}" I would get empty field
value="{{ old('amount_paid','test') }}" I would get 'test' in the field
I'm using Laravel 5.6
EDIT
to clarify the above code it to debug
this is my original code
controller
return back()->withInput();
view
<div class="form-group">
<label> amount paid </label>
<input type="float" class="form-control" name="amount_paid" value="{{ old('amount_paid')}}" required>
</div>
adding the method that handle the request
public function store(Request $request)
{
// updating the amount paid
$rent = new Rent;
$rent->amount_paid = $request->amount_paid;
try {
$rent->save();
} catch (\Illuminate\Database\QueryException $e) {
//return to the form and populate it
return back()->withInput();
}
return redirect('units/'.$request->unit_id);
** update **
It appear that session->flash is not working.
I tried a new installation of laravel and it is working fine
The problem was related to session it self.
I have 2
\Illuminate\Session\Middleware\StartSession::class,
one in middleware and another in $middlewareGroups[web].
this was a result of following a tutorial in youtube months ago to implement localisation :(

PHP Laravel Validation data key names

I got such problem.
What I want to do - is to make 1 place for validation rules for a user data. These data consists of Patient, Address and other objects.
So I created rules:
protected function validationRules()
{
return [
'Patient.firstName' => 'required|string|min:2',
'Patient.lastName' => 'required|string',
'Patient.sex' => 'required|string',
'Address.city' => 'required|string',
'Address.states' => 'required|string',
'Address.address1' => 'required|string|min:2',
'Address.zip' => 'required|string|min:2',
'Phone.mobileArea' => 'string|min:3|required_with:Phone.mobilePhone',
'Phone.mobilePhone' => 'string|min:7|required_with:Phone.mobileArea',
'Phone.homePhone' => 'string|min:7|required_with:Phone.homeArea',
'Phone.homeArea' => 'string|min:3|required_with:Phone.homePhone',
];
}
In form i have inputs like
<input id="firstName" type="text" class="form-control" name="Patient[firstName]" value="{{ $user->getFirstName() }}" required autofocus placeholder="First Name">
And on save everything works correctly.
The code
$this->validate($request, $this->validationRules());
Performs validation very well. BUT....
On another place, when I want to show that some information is missing in the user profile, I perform such validation and its failed:
$validator = Validator::make([
'Patient[firstName]' => $user->getFirstName(),
'Patient[lastName]' => $user->getLastName(),
'Patient.lastName' => $user->getLastName(),
'Patient->lastName' => $user->getLastName(),
'Patient.sex' => $user->getSex(),
'Address.city' => $address->getCity(),
'Address.states' => $address->getState(),
'Address.address1' => $address->getStreet1(),
'Address.zip' => $address->getZip(),
'Phone.mobileArea' => $mobilePhone->getArea(),
'Phone.mobilePhone' => $mobilePhone->getNumber(),
'Phone.homePhone' => $homePhone->getArea(),
'Phone.homeArea' => $homePhone->getNumber(),
], $this->validationRules());
As you can see, i tried different variations of naming Patient->lastName key in data array. But i still have error that last name is required.
When i print validator i can see such structure:
Validator {#300 ▼
#data: array:12 [▼
"Patient[firstName]" => ""
"Patient[lastName]" => "Colohanin"
"Patient->lastName" => "Colohanin"
"Patient->sex" => "female"
"Address->city" => "GOSHEN2"
"Address->states" => "NY"
"Address->address1" => "Aleco Russo 59/1 a.68"
"Address->zip" => "109242"
"Phone->mobileArea" => "793"
"Phone->mobilePhone" => "906990"
"Phone->homePhone" => "022"
"Phone->homeArea" => "3322278"
]
#initialRules: array:1 [▼
"Patient.lastName" => "required|string"
]
}
As I understand, the validator has rules for "Patient.lastName" but in data array Laravel transform this key to object and Validator can't find this key in data bag. In result, I have error - > patient last name required(for testing purposes, I removed other rules)
So there is my question. Does anyone know, how to set data array in "dot" sintancs? How should i name "Patient.lastName" in data array(first parameter in Validator::make())?
The rewriting keys using underscore doesn't accept(patient_firstName)
Suddenly i found that laravel helper have array_set helper for such arrays.
So in result:
$data = [
'Patient[firstName]' => $user->getFirstName(),
'Patient[lastName]' => $user->getLastName(),
'Patient["lastName"]' => $user->getLastName(),
'Patient.lastName' => $user->getLastName(),
'Patient->lastName' => $user->getLastName(),
'Address.city' => $address->getCity(),
'Address.states' => $address->getState(),
'Address.address1' => $address->getStreet1(),
'Address.zip' => $address->getZip(),
'Phone.mobileArea' => $mobilePhone->getArea(),
'Phone.mobilePhone' => $mobilePhone->getNumber(),
'Phone.homePhone' => $homePhone->getArea(),
'Phone.homeArea' => $homePhone->getNumber(),
];
Fails validation, but if you add elements throw array_set helper it helps
array_set
array_set($data, 'Patient.lastName' , $user->getLastName());
After that, validation by lastName is no longer fails.
Hope it helps somebody
try this:
$this->validate($request->get('Patient'), $this->validationRules());
form input:
all name changes it to :
<input id="firstName" type="text" class="form-control" name="Patient[firstName]" value="{{ $user->getFirstName() }}" required autofocus placeholder="First Name">
<input id="mobileArea" type="text" class="form-control" name="Patient[mobileArea]" value="{{ $user->mobileArea() }}" required autofocus placeholder="mobileArea"
>
and change all validationrules using:
protected function validationRules()
{
return [
'Patient.firstName' => 'required|string|min:2',
'Patient.lastName' => 'required|string',
'Patient.sex' => 'required|string',
'Patient.city' => 'required|string',
'Patient.states' => 'required|string',
'Patient.address1' => 'required|string|min:2',
'Patient.zip' => 'required|string|min:2',
'Patient.mobileArea' => 'string|min:3|required_with:Patient.mobilePhone',
'Patient.mobilePhone' => 'string|min:7|required_with:Patient.mobileArea',
'Patient.homePhone' => 'string|min:7|required_with:Patient.homeArea',
'Patient.homeArea' => 'string|min:3|required_with:Patient.homePhone',
];
}
Hope it help

Resources