Introduction
We will be creating a form and submiting the data to the databse. Our AIM is to learn how we can fetch the data from the form and submit in the form. We will not discussing about the form data validation.
You should not keep the expectation that you will learn about the form validation.
We will break the complete article in 6 parts. In every part we will do something new and if you face some problem you can comment the step number with the error. We will be happy to help you.
Step # | Task |
---|---|
Step 1 | Creating Routes |
Step 2 | Creating Forms |
Step 3 | Creating Controller |
Step 4 | Creating Database Modal |
Step 5 | Connecting to database |
Step 6 | Saveing and Fetchind data from Database |
Step 1
Create a new project, so that we will be on same page and there will no conflict. We will talk in same langauge and there will same default page and default data.
When you will open the routes/web.php
you will see this code.
Initial Code
- Create two different route.
- First Route will show the form.
- Second Route will accept the form data and savve to the database.
Updated Code
Step 2
Now we have two routes, it’s time to crete the form. So, In this step we will create the form.
Now we have a form, it’s time to show that form.
Now open your application and goto your localhost:8080/product
. If you see the form it means you are with me.
Doing CSRF things in laravel is very easy. There is a @csrf
directive which help us in protecting our website from XSS. I know this might be new for some of you that’s why I added one simple code snippet which will help you in understanding How to use CSRF in Larave ?
You just have to use @csrf inside the html form, that’s it.
After adding the
@csrf
token your code will look like this.
Step 3
Now we will create a controller and handle all our action from there.
Let’s open the controller. I hope you know the location of the controller.
We will create total 6 method for six differnt things
Method Name | Functionality |
---|---|
index | Show Form |
createProduct | Save Form Data [Create] |
allProducts | Read All Form Data [Read] |
modifyProduct | Modify Form Data [Update] |
deleteProduct | Delete Form Data [Delete] |
oneProduct | Show One Form Data |
Now we have Controller for each routes. let’s remove the anonymous function from the web.php and update the code with controller methods.
Step 4
Let’s create the Migraion file.To Create the migration file using Command.
When you will run the above command it will tell you then name of your migraion file. Migration file name is based on the current date, which means your file name will be not safe as mine.
Migration file is only useful it’s name is useless for us. We don’t refer this filename anywhere.