Laravel + VueJS: Handling error messages

Tram Ho

Introduce

Hi everyone, this is the first in a series of Laravel (6.x) and VueJS series I will share in the near future. In this topic, I will guide you to use VueJS (on the frontend) to handle errors returned by Laravel (on the backend) or in other words called Server Validation. ? . All of this series, I think, is the basic knowledge, but for those who are new to these two subjects and want to combine them together, it will be necessary. Let’s start with it,

Environment settings

Laravel Install

At the time of writing this article, I am working on Laravel 6.7. XD Create .env file and key ?

Remember to edit the database in the .env file. Next I have used the make:auth command of Laravel to create quick demo templates, note that Laravel 6.x onwards wants to create make:auth then you Create the way below

Edit the code

Ok next, when you run the composer command above to install make: auth, laravel has already created for you the necessary components of Vue. The auth template is in those resources/views/auth . ? The part of demo validate in this tutorial will be the laravel’s registration page, you will notice it will be processed in Controller app/Controllers/Auth/RegisterController.php including the validate section Now I will correct it A bit of register.blade.php with app.js for Vue

app.js

Above I have created an Errors class to facilitate the handling of complex errors later: d, you should create it into a separate file. Variable fields in data will store all fields on the form. and the errors variable is an instance of the Errors class, I used axios to call the api if it failed I would throw the returned data into this variable. On the register.blade.php file, I modified it as follows

Above I have a span tag whose class is invalid-feedback this card will contain an error message through the errors variable that calls the get function and passes the faulty params defined in the validate section of RegsiterController. write vuejs in .blade.php file, so I want to call VueJS variables so that I don’t get confused with Laravel’s add @ before the {{.

It is done ? Run now

and access localhost: 8000 / register to enjoy the memory ? Here are my results:

You can refer to the source of the article here: https://github.com/hieudt/laravel-vuejs-handle-error Sincerely, see you in the following articles. ? Do not forget to leave 1 + up vote if you find it useful or have questions or contributions, please comment below

Share the news now

Source : Viblo