Creating A Laravel Contact Form Package

In this tutorial we're going to create our own Laravel package that will give you all the functionality you need to add a contact form to your website. If you want to learn more about building your own Laravel packages you can view a previous tutorial here.

A contact form is something you'll have on most of the project you build it allows your visitors a quick way of contacting you with any feedback or problems. The problem is if this contact form is open to the internet then you have to be careful about spam. Therefore in this package we're going to create the contact form using VueJS with a API to send the email.

Composer JSON

The first thing you need to do when creating a package is to add your composer.json file for the package. This needs to go at the root level of your package and will create the namespace for the package.

Contact Form Service Provider

The main PHP file in your package is the service provider /ContactFormServiceProvider.php it tells Laravel what your files are and how to use your package. In this file we need a boot method which will create the API route and a location to publish the VueJS component.

Contact Form VueJS Component

The VueJS component will be located in /Resources/assets/js folder. The below code will create the contact form in VueJS and send the formData to the API route of the contact form using the axios library.

API Routes

As we have an API route we need to create a route file at /Routes/api.php. We only need one API route that will be a POST to /api/contact and will send the request to the ContactController.

Contact Controller

We'll need to create a controller folder located in Http/Controllers inside this folder we can then create a ContactController.php. This file will need a store method which will validate the request and send the email and return with a JSON of success.

You'll notice there's a \Paulund\ContactForm\Mail\ContactEmail object which is used to send the email and we pass in 'name', 'email', 'message' from the request so we can send them to the admin email address.

Contact Form Request

You'll notice in the ContractController::store method we're passing in a ContactFormRequest object. This will inherit the FormRequest class which is used to validate the request but adding a rules method.

This will make sure that the request object inside the controller is validated correctly.


In the ContactController we call the ContactEmail object so we need to create that email object, passing in the array of the contact form information.

Mail Resources

We'll need to create a view file for the email resource located at /Resources/assets/views. In the ContactEmail class we use the markdown method to call a view resource of this will need to show the name, email and the message.

This is everything you need to create a Contact Form Laravel package. If you put these into your own package you can have a quick contact form in your project.