Reputation: 309
I'm trying to display the errors in the correct order (based on the index) from the response I have in laravel api.
Errors displayed on vue using {{ errors }}
:
{ "options.cart.0.request": [ "options.cart.0.request es is invalid." ], "options.cart.3.request": [ "options.cart.3.request is invalid." ] }
Function that calls the api - Response Status code that I get is 422 :
async doOrder () {
axios.post('api/order', this.user).then( response => {
this.$store.dispatch('auth/updateUser', { user : response.data })
}).catch(error => {
if (error.response.status === 404) {
this.$router.push('/404');
}
if (error.response.status === 422 ) {
this.errors = error.response.data.errors
}
});
Laravel Validation :
public function store(Request $request)
{
$input = $this->validate( $request, [
'options.cart' => 'required|array',
'options.cart.*.code' => 'required|exists:products,code',
'options.cart.*.request' => 'required|in:1,2',
]);
return $request; //Testing
}
Vue v-for :
<section id="request" v-if="user.options.cart.length > 0">
<div class="card-body" v-for="(object , index) in user.options.cart" :key="object.product_id">
<div class="col-6 col-sm-6 col-md-8 text-md-right form-group" style="padding-top: 5px">
<select class="custom-select my-1 mr-sm-2" :class="errors ? 'is-invalid' : ''" name="request" required v-model="object.request">
<option value="1" :selected="object.request == 1 ">Amostras</option>
<option value="2" :selected="object.request == 2 ">Informações / Cotação</option>
</select>
<div class="invalid-feedback" v-if="errors.errors">Example invalid custom select feedback</div>
</div>
</div>
</section>
Upvotes: 2
Views: 2116
Reputation: 167
please follow along,
in your controller
$request->validate([
'ClinicName' => 'required|string|min:200',
'Branches.*.BranchName'=>'required|string|min:200'
]);
in your vue3 file, to access the errors which will have keys such as, 'Branches.0.BranchName' then you can access the above error with for loop similar to this
<p v-if="form.errors['Branches.' + counter + '.BranchName']"
class="mt-2 text-sm text-red-600 dark:text-red-500">
{{ form.errors["Branches." + counter + ".BranchName"] }}
</p>
here the counter can be any counter starting from 0.
Upvotes: 0
Reputation:
you will need to use validator facades like this
$validator = \Validator::make(request()->all(), [
'options.cart' => 'required|array',
'options.cart.*.code' => 'required|exists:products,code',
'options.cart.*.request' => 'required|in:1,2',
]);
if($validator->fails()){
return response()->json(['status' => false, 'data' => $validator->errors()]);
}
Upvotes: 1