Laravel 5.8 – From The Ground Up - Laravel 5.8 Tutorial From Scratch – e19 – Handling a Contact Form Using a Laravel Mailable

Education, Programming

Laravel 5.8 – From The Ground Up

52 Lessons

Laravel 5.8 Tutorial From Scratch – e19 – Handling a Contact Form Using a Laravel Mailable

up next in our learning I want to start talking about sending emails another important task that most websites need to do we're going to start from the

basics and later on when we start talking about events and jobs we're gonna be able to do this in a much faster way for the user but for now we're gonna do it inline in our project

we have this contact us page and right now we're not doing anything with it my idea is to turn this page into a form that someone can fill out and send us an email from fairly simple and straight

forward most websites actually do this so let's tackle this real world example right now so what is our first step as we've learned before we need a controller and then we're going to need

some routes let's start with our controller PHP artisan make controller contact form controller alright so we have our controller now the first thing I want to do is I want to refactor our

web route to start using this controller you see right now all we are doing is showing a view we're not actually fetching a controller so let's rewrite this right now to use that controller

route get contact and we're going to be using the contact form controller at create so why are we using the method creates well you got to remember that create is what displays the form so in

continuing with restful controllers we got to find the appropriate verb for a current action we can think of a contact form as the create method similarly to our customers and new customer right

this is our create method so of course our contact even though we're not gonna call it contact slash creates it goes to our create write and that's what makes sense it's a form it's being displayed

it wants to create a record in our database and send us an email of course so we need to call it the create method so there it is so we're using the create method this is a little bit tricky I

gotta admit first is difficult to find the correct verb for each of the actions and a lot of times what you will find is that you're not using enough controllers as

you get more and more experience you'll actually find yourself using tons of controllers and sometimes your controls will only have two or three methods in them and each method will only have one

or two lines of code but that's the beauty of controllers they're free you can make as many of them as you want and as long as they're named appropriately it's very easy to have many controllers

so with that being said let's get rid of our old contact so we need to go to this create method now my contact form controller and let's create that method now public function create and for now

we're just going to return a view and we're gonna have to move our view right now let's go into resources views right now our contact page is just called contact that played that PHP but we know

we're gonna have to move that into its own contact directory or you can even call it contact form if you want it to and then inside there we'll have a create view in my case I'm just gonna

say contact create and I think that'll make sense so let me go ahead and create that directory now new directory contact and let's move our contact form into contact and let's rename it refactor

rename create okay let's go into the create and let's actually just check it out in the browser first we're still all set with that all right so I'm gonna borrow some logic from our previous form

that we've been working on just because I have this nice and setup already so I will bring that over let's put a form right here we'll worry about the action in just a second so we'll have a name

and email and we need a message as typical forms will be so this would be a label for message will say message and it's not going to be an input this will be a text area name of message and let's

give it a class of form control all right if you have any errors for message so the last thing I do want to do is of course if validation were to fail we do want to put our old data back

in so old message now we have worked in this section here before but we're actually not gonna need any of that so we can simplify everything to just look like so reformat so our form is looking

good we have three fields name email and message let's check it out on the browser see what we have refresh and there we are okay so we have our name our email and our message everything's

looking good alright let's add our final step of course we need a button all rights a button of type submit' and let's add some classes here BTN and BTN may be primary and then we'll say send

message all right let's see there it is so we have our contact form okay so let's talk about our form action where is this gonna be posting to if you remember in our previous lesson our

create method actually posts to just the base contact but using post so let me create that route right now so we're gonna post to contact and that is gonna hit our store method contact form is

create method and then it posts to our store method remember typically this will have a create attached to it but because we're dealing with just a simple contact form we're not going to do that

to the URL so we'll keep it like that and that's okay so we're going to be posting to slash contact with a method of posts and one last little bit is of course we need our CSRF field so CSRF

and that's it that way laravel won't fail so this will post and this will come to our controller and this will be calling this store method so we'll have the store and for now I'm just gonna die

and dump the request just to show you that all of our data is there so request all it's what we reduce let's see if we can make it work refresh

new customer new email our message okay send message and there we are so we have our name our email and our message great so what's the next step of course validation let's validate this request

so we'll say data is equal to requests validate and we have three fields so we have our name of course your name is required then we have our email which is required and it needs to be an email

oops email there we go and then we have our message which is just simply required that's our message and that all right so then if we get to this step then of

course this is where we need to send an email and we'll get to that in just a second let me just confirm validation is working we head back I'm gonna hit refresh and I'm just gonna hit the forum

and sure enough the name field is required the email fields required and the message field is required okay so let's talk about sending an email laravel ships with something called May

labels and think of available as a template that's ready for you to start sending nicely formatted emails right out-of-the-box we could start by sending emails the very plain way where we're

actually doing everything by hand but I just don't find the value in that when most the time you're really gonna use the mailable in a more advanced topic we can talk

about how to create your own mail and what the benefits of doing that would be but for most cases Mela bowls are perfectly fine and you won't have to reinvent the wheel from scratch which is

why you're using layer well to begin with right you want everything to be simple so let's head back over to our terminal and let's run PHP artisan and let's find the command so of course this

will be a make command because we're making something and we have that right here make mail it creates a new email class let's run PHP artisan help make mail and

let's see what kind of options we need at the very least we need a name but there are some options and specifically there's this markdown option it creates a new

markdown template for the mailable now these markdown may labels was something that was introduced a little while back in level and ever since it has been extremely easy to create very

good-looking emails right out of the box so let's run the command again and we'll say PHP artisan make mail what are we gonna call our mail well it makes sense to call it contact form mail and then

we'll pass in that markdown flag this markdown section will actually create a view for our mail and that's the way that mailer bows work with markdown it creates a view and you can actually take

a look at the view in your browser and preview your email it's really really convenient but it creates a view inside your views directory but this view is not used for your browser of course as

every other view in there so what I like to do is nest them inside its own email folder that way the email folder will contain all of my mail views inside and I know as long as it's inside that

directory I don't have to worry about it so I use the following convention emails after emails I use the exact same convention as we've been using before so my next step will be contact so that way

it follows the same convention but inside the emails subdirectory so contact and then what are we going to call this contact form all right let's give it a go let's go back to phpstorm

and see what we got so we have again this new emails directory that we just created and then we have contact which matches the view for contact and then inside of that we

have our contact form and if we open our contact form we get this pre-made email we'll take a look at that pre-made email in just a second but for now let's ignore that so how do we send this email

now for testing purposes there are services like mail trap which we're going to use today which will basically show you an inbox and you could use it for testing once

you deploy into a real server you'll probably use something more like mailgun or something like that to actually send your emails but for the purposes of development mailtraq works amazingly so

we'll use that today but let's start with the first step the coding part of it so how do we send an email so we have this view here but if you actually go up

to app you created a new folder called mail when you ran that command so we have this contact form mail and this is the one that actually calls that contact form notice that it looks a lot like how

we call views except that is calling this markdown and then it's going into emails contact and then our contact form so this is the class that kind of handles everything for us you see it

extends mailable all right let's get this email sent let's say mail and we're using illuminate support façades mail and if we look up top it imported it up here right so it's mail but you have to

add the use statement up here now phpstorm of course does this automatically which is nice so we're gonna send a mail to and what's the email we're gonna send it to well for

now I'm just gonna send it to test a test comm not a real email address and we're gonna send a new contact form mail and that's it laravel is now able to send that email it really is that simple

so let's go through the steps one more time so we're sending a mail and this mail facade is being imported up here at the top if you get an error like mail doesn't exist the class then that means

that you did not import it at the top so send me an email too and then this is the email address that we're gonna use for now send the new contact form mail and contact form mail also get imported

up here as app mail contact for mail so technically if we ran this right now it will send an email however we don't have any email setup so we need to go to our EMV file which is remember where we have

all of our settings and there's this section here for mail and we have not really used it up until this point so it actually comes set up for using mail trap but the

username password is empty it's no which means that we actually have to set this up so what you will need to do is go to mail trap dot IO and create an account in mail trap I've already created an

account it's very simple to create so I won't run through the steps of that but once you have mail trap again this is for email testing this is for development you would never use this in

production but this will help you create emails and send them to yourself so you can see them right away once you're in here and by the way mail trap is free there are some premium

services that you can pay for but for the most part the free version works perfectly fine once you're inside your dashboard you will have this demo inbox if you click in demo inbox you will see

your credentials down here these are my credentials you need to have your very own credentials otherwise you wouldn't be sending emails to your mail trap account you'll be sending them to mine

and then you'll never see them so make sure that you get your own account and you create your own numbers so user name will go ahead and copy this over paste and then let's take a look at the

password copy and then paste and that's it setup is done for mail trap you don't have to do anything L live L kind of ships ready to go for mail trap let's fill out our form and let's see if we

can actually get an email sent to us new customer new email testing Mela Bulls in laravel all right let's see what happens send message okay we're not returning a view or a thank you message or anything

like that so that's why we're getting this white page but if we visit mail trap there we are contact form mail and we have sent ourself our very first email through laravel obviously this

view hasn't been modified this is what it ships with so let's go ahead and change that now remember inside our views directory we have our emails and then we have this contact form so this

is what actually got sent to us right makes sense we have this introduction the body of your message thanks layer so introduction body of message and then

we see thanks and then a config name app which we have not set up and ships as laravel great so how do we get the form data to our mailable so that's the next step a lot like how you pass data to a

view you need to pass the data into our mailable so let's go back to our controller contact form controller and we have this data but we are not passing it to our mailable so you pass it right

here data that's where the data goes so you're passing contact form mail and in the parenthesis we'll pass the data so let's go to contact form mail and let's accept that data so we'll say data up

here let's initialize the fields and here's the cool bit of this we have this private data but if we make this public now that data object is actually available to our view we can just simply

call data and it will work so let's do that now back in our blade let's erase all of this for now the only thing you really need is just this component mail message that's all that you need so

let's say thank you for your message and in this file this is markdown so you could use a mixture of markdown or even HTML so I could say strong name and then how do we output the name well we have

that data let's just call name name is simply just a form name that we had so we have our name we have our email and let's just have our message and I'll just output that right on the body data

message all right let's give that another run back to Chrome I still have my post here so I'm just gonna hit refresh hit continue and that's just send us another email and see if it

comes in right here there it is open it up and there we go so we have thank you for your message name new customer new @ email testing may levels in level great the very last thing I

just want to touch up on is in our controller after we hit this door method the nice thing to do is to display a thank you message of some sort but for the purposes of demonstration I'm just

going to return or redirect and let's go back to our contact that way we see the form again so let's try that one final time refresh and we should be headed back to contact and there we are so it

simply just returns back now we are not giving our users any feedback at all which will bring us to our next episode where we're gonna be talking about flashing data to our session so we can

show things to our users such as a thank you message for filling out the contact form so stay tuned

Having a contact form where a user can submit their contact request is a very common thing in today’s modern websites. Follow along as we add a contact form and use a Mailable to send an email.

For the best experience, follow along in our interactive school at https://www.coderstape.com

Resources
Course Source Code
https://github.com/coderstape/laravel-58-from-scratch
https://mailtrap.io/

Hit us up on Twitter with any questions or comments @codertape (https://twitter.com/CodersTape)

About This Course

Ready to get started on your path to Laravel Artisan? In this series, we are breaking down all of the basics of Laravel to get you comfortable using the world’s most popular PHP framework. Let’s get started!

    add to database laravel admin laravel artisan Artisan Command artisan commend create artisan console artisan laravel command authentication in laravel belongsto belongsto laravel example coding tutorials create artisan command create command artisan create new command artisan Create your own crud laravel crud laravel tutorial crud resource laravel crud with file upload custom artisan commands custom artisan commands laravel custom laravel database configuration laravel database relationship digital ocean dotenv eager loading eager loading in laravel eager loading vs lazy loading laravel eloquent eloquent accessors eloquent mutators eloquent orm feature testing laravel fetching data in laravel filesystem laravel form requests full stack vue gate and policy laravel google optimize hasmany hasmany laravel hasmany laravel example hasmany relationship in laravel hasone hasone relationship in laravel How to create how to queue email how to use queue installing laravel intervention image laravel laravel 5 laravel 5 auth laravel 5.4 queue laravel 5.5 queue laravel 5.8 laravel 5.8 artisan command laravel 5.8 artisan console laravel 5.8 auth tutorial laravel 5.8 authentication laravel 5.8 commands laravel 5.8 crud laravel 5.8 crud example laravel 5.8 custom middleware laravel 5.8 deprecations laravel 5.8 eager loading laravel 5.8 elixir laravel 5.8 event listeners laravel 5.8 events laravel 5.8 feature laravel 5.8 features laravel 5.8 global middleware laravel 5.8 install laravel 5.8 lazy loading laravel 5.8 listeners laravel 5.8 middleware laravel 5.8 multi auth laravel 5.8 named resource routes laravel 5.8 named routes laravel 5.8 new feature laravel 5.8 own artisan command laravel 5.8 queue laravel 5.8 queues laravel 5.8 routing laravel 5.8 telescope laravel 5.8 tutorial laravel 5.8 user auth laravel 5.8 user authentication laravel 5.8 what's new laravel 5.9 laravel admin permissions laravel api laravel artisan command laravel artisan console laravel assets laravel auth laravel auth role laravel authentication laravel authorization laravel axios post example laravel background process laravel background task laravel background worker laravel beginner to master laravel belongsto laravel belongsto vs hasone laravel belongstomany laravel best packages laravel best practices laravel best tutorial laravel bootstrap laravel command laravel command line laravel commands tutorial laravel composer install laravel connect db laravel console command laravel console testing laravel contact form send email laravel controllers laravel create laravel crud laravel crud policy laravel custom command laravel custom middleware laravel database laravel database configuration laravel database relationships laravel database seeder laravel database settings laravel db seed laravel db settings laravel debugging laravel deploy aws laravel deploy digital ocean laravel deploy on digitalocean laravel deploy on server laravel deploy to production laravel deployment laravel digitalocean laravel drag and drop file upload laravel dropzone file upload laravel dropzone image upload laravel e-commerce laravel eager loading laravel eager loading tutorial laravel eager loading with condition laravel elixir laravel eloquent laravel eloquent belongsto laravel eloquent crud laravel eloquent hasmany laravel eloquent where laravel eloquest tutorial laravel events and queue laravel events tutorial laravel factory laravel feature test laravel feature testing laravel fetching data from database laravel file storage laravel fillable example laravel flash message notification laravel for beginners laravel form validation laravel forms laravel forms bootstrap snippets laravel from scratch laravel from the ground up laravel front end laravel frontend tutorial laravel gate and policy tutorial laravel global middleware laravel hasmany laravel hasone laravel i18n laravel installation laravel installation mac laravel intervention image tutorial laravel javascript tutorial laravel jobs queue laravel language laravel language switcher laravel language tutorial laravel languages laravel lazy loading laravel listener event laravel listeners laravel localization laravel login laravel mailable tutorial laravel many to many relationship example laravel markdown email laravel markdown mail laravel mass assignment laravel middleware laravel migrate fresh laravel mix laravel mix 5.8 laravel mix vue laravel model factory tutorial laravel multiple language laravel mysql json laravel named resource routes laravel named routes laravel new features laravel news laravel nginx laravel node modules laravel npm install laravel npm run watch error laravel one to one laravel paginate laravel paginate link laravel pagination laravel pagination 5.8 laravel pagination links laravel pagination tutorial laravel phpunit laravel phpunit testing laravel pivot table example laravel policy laravel preview laravel query optimization laravel queue laravel queue event listener laravel react laravel register user laravel registration laravel registration validation laravel relationships laravel reset password laravel role middleware laravel role permission laravel roles laravel route group middleware laravel routes laravel routing laravel routing with parameters laravel sass laravel save file to database laravel scopes laravel seo tutorial laravel server laravel session data laravel ssl laravel supervisor laravel tailwind css laravel tailwind setup laravel tdd laravel tdd tutorial laravel telescope laravel telescope installation laravel telescope tutorial laravel test driven development laravel test workflow laravel testing laravel testing controllers laravel testing tutorial laravel tools laravel translation laravel tutorial laravel tutorial for beginners laravel ubuntu server laravel ubuntu tutorial laravel unit testing controllers laravel upload file laravel upload image to storage laravel upload multiple files at once laravel upload multiple image to database laravel upload multiple images laravel url slug laravel vue laravel vue js crud laravel vue setup laravel vue tutorial laravel vue.js laravel webpack error laravel webpack tutorial lazy loading lazy loading laravel lazy loading vs eager loading learn laravel learn laravel framework step by step localization in laravel localization laravel many to many laravel mvc tutorial for beginners in php mvc tutorial laravel mysql mysql relational database mysql relationship n + 1 problem n + 1 problem laravel new artisan command npm install npm run dev npm run watch laravel one to many one to one one to one laravel own artisan command pagination pagination bootstrap pagination bootstrap php mysql pagination laravel pagination laravel bootstrap pagination links pagination php php php artisan php carbon immutable php framework php framework 2019 php what's new 2019 phpunit phpunit laravel phpunit testing pivot laravel policy laravel polymorphic relationships queue and events queue email queue for laravel queue jobs queue laravel 5.8 registration form relationship laravel eloquent relationship mysql restful controller role permission in laravel roles laravel route model binding laravel routing in laravel save image to database seo friendly seo friendly content writing seo friendly website seo laravel seo optimization simple pagination laravel slugify sqlite relational database sqlite relationships between tables symfony command console symfony laravel tailwind css tailwind laravel mix telescope laravel tutorial laravel unit testing unit testing laravel upload file laravel upload file php upload image laravel upload image to database php upload images laravel upload multiple files in php url slug laravel url slug php vue vue.js vuejs laravel why use laravel queue why use queue