Laravel 8 + Vue.js 3 CRUD with Composition API
We will learn how to build a small web application that creates, reads, updates, and deletes MySQL database. In addition, we will learn how to create tables, controllers, views, models, API routes and working with the axios library to send a network request. Laravel is providing VueJS support out of the box. Creating a crud boilerplate with Vue and Laravel is very easy. The Laravel community has produced a ton of valuable educational resources, including this one!
This approach offers some significant benefits: It enables you to separate the backend and frontend projects and deploy them independently using the different strategies and schedules for testing and deployment. We can deploy the frontend as the static application to a CDN and achieve virtually unlimited scaling for a fraction of the cost of hosting it with the backend.
For this vue laravel crud demo, we will not create separate projects for the frontend because Laravel provides the best support for Vue. In this SPA, you can create a post, edit the post, read the post, and delete the post. Now, first, we need to install the Laravel application. So let us install a new Laravel by the following command.
Step 1: Install Laravel boilerplate. I am using the Visual Studio Code. Setup the database configuration inside the. Now, start compiling assets using the following command. Type the following command to install the vue-router and vue-axios dependencies. The vue-router is used for routing our Vue. Modify with the following code inside the app. Add the following code inside the post. So we need to define the following route, where we can push any route, and then it will give the correct route without any error.
Otherwise, it will give the error because, in Laravel, you have not defined any route; it is the Vue where you have defined the various component route. Due to the following code, now you can be able to use the Laravel route proxy as a Vue route, and you can display the Vue components depending on the current URL. You can see that we have successfully integrated the Vue component in our Laravel application. Then we have created a router object and passed it to our Vue application.
It is the directive that will render the component according to the current URL. Save the file, and if your npm run watch is not running, then you might need to compile again and then go to the browser and go to these URLs for testing and see if the project is working or not. Step 5: Create a Navigation bar Write the following code inside the App. I have added the navbar. Next, we will add the Bootstrap Form to create a post.
Post Title and Post Body. We have made one method called addPost. So, when a user submits the form, we will get the input inside the addPost method. I am skipping the validation of each field because this article is getting long and long. So we will do it in another post.
Then, you can see the form below. So, first, we will create a schema for the post table. Then, also, we need a Post model. So let us create a Laravel Resource Collection using the following command. First, we define the function that stores the data inside the MySQL database.
Now, we have created the backend. Write the following code inside the CreateComponent. Now, display the posts. So let us edit the IndexComponent. Now, here, we need to write the data because axios are by default, wrap our backend data posts with data, and use the Resource Collection. So it will also wrap the data in the data key. So to get the actual data, we need to write like response.
If we have not used axios, then we might write the response. Step Send edit and update request Now, when our edit component loads, we need to fetch the data from the server to display the existing data. Then, after changing the data in the textbox and textarea, we hit the update button, and we call the updatePost function to send a post request to the server to update the data.
Step Delete the data. Now, the only remaining thing is to delete or remove the data from the database. So, let us write the final code inside the IndexComponent. Thanks for taking it. You can use the following Github Code for reference.
vue axios is not defined
Notice: the link to the final repository is at the end of the article. We install Vue. Next, we need to enable the vue-loader, and in the webpack. Before: After: mix. Now, we need to create our first Vue. We will have three routes: company index, create, and edit forms. It allows you to divide the parts of the component to separate files, to then be re-used.
The problem appears in larger projects, but I would advise using it even on smaller projects like this one, to get into the habit of separating the concerns, and make code more readable. Options API. Next, we use axios for the API requests, which is by default included in Laravel installation, we just need to import it and can make the requests like axios.
Next, what is that ref thing? The next thing to notice is that we use Vue Router to redirect to the list, by its name companies. In case of validation errors with code , we parse the error structure and turn it into a String variable of errors.
Finally, we define what we return from the Composable file — all variables and methods. The script part is more interesting. We add destroyCompany to be fetched from the Composable file, we also define a local method deleteCompany, which in turn calls that composable method of destroyCompany, and then calls to getCompanies again, to refresh the table.
So, see, how we re-use the Composable file, without polluting the main component? This is one of the benefits of Composition API. Next, the saveCompany method will be a local component method, which, in turn, calls the Composable method of createCompany. In case of validation errors, we have errors string with all the errors, separated by a space symbol. The result looks like this: And if all goes well, we are automatically redirected but without reloading the full page to the list of companies.
It is done in the Composable file, by router. Then, we use it inside of setup props and call the Composable methods with that exact parameter: getCompany props. Next, in the create form we had a form variable that we defined as an object with keys and empty values. Now, you see the beauty of Composition API? The submit and validation parts work absolutely identical as the create form: redirects to the index in case of success, or show the error in case of the validation error.
But that was exactly the point — to give you a head start, from here you can read more about Vue and API, and practice more complex scenarios. Like our articles?
Authentication best practices for Vue
How To Use VueJS with Laravel Blade
For example, the sidebar that displays how many replies there are needs to update in real time. But wait. We are using Vue components all the way now, so what do we do? You lose all those nice little helper and convenience functions built into blade.
So we can just remove the element from the array in Vue, and the page will update automatically for us. No need to use jQuery in this case. Children Fire Events, Parents Listen To Events In order for a child component to communicate with a parent componentthat child must emit an event. So what we are going to do is add the highlighted line below in Reply.
Well that would be Replies. Speaking of Form Data, it can get pretty cumbersome as you add fields to your form. So I created a mixin! Transforming to Form Data Getting Cumbersome?
Vue i18n: Building a multi-lingual app
I wrote a VueJS mixin for that! Can you find it? We will touch on it soon! The first parameter of this mixin is the form see quick tip. This is all of the data you will be sending to the server. Typically this is in JSON object that we will iterate over and transform to form data. Next up, we have fileKeys.
POST, PUT & PATCH Requests with VueJS and Axios
This is an array that identifies any of the keys in your form array that are files. We want to handle those in a special manner. Finally we have the method parameter. By default this is an empty string. We will go through an example in the next section. If you have a checkbox that you want to send to the form and the value is true or false these will be sent as a String.
We went to send these as a 1 or a 0 so we can perform any necessary operations on our backend. Hopefully this helps! Well they are actually both good solutions, with their own advantages and disadvantages. This post and this page answer this question pretty well.
The important bits are: Token state being initialized by its local storage value, if possible. The Authentication request action returns a Promise, useful for redirect when a successful login happens. Good practice: pass the login credentials in the request body, not in the URL. The following example uses Axios and its default headers. All your API calls are authenticated!
And when logging out, we delete the authorization header. Auto-authentication Right now if we refresh the app, we do have the state correctly set to the previous token.
In your main. Authenticated routes Now you probably want to restrict access to your routes depending on whether they are authenticated or not.
Here we use navigation guards. They allow us to put conditions on routes access that we use to our advantage in conjunction with the Vuex store.