DEV Community

Cover image for Laravel101: Create and Submit a Form to the Server
Kazem
Kazem

Posted on

Laravel101: Create and Submit a Form to the Server

In the previous tutorial, we learned how to connect a SQLite database to our Laravel application. We created a table using migration and saved a record in the tasks table using the tinker. Now, let's create a simple form to save a new record in the database.


To begin, we'll add a basic form to inside another page. I just need a simple form as follow:

<form>
   <input type="text" id="title">
   <button type="submit">save</button>
</form>
Enter fullscreen mode Exit fullscreen mode

Please note that this form doesn't currently send any data on its own. To make the form submit its information when the button is pressed, we need to add two attributes to the form tag. First, we specify the request method we want to use, which in this case is POST. Second, we provide the server route where we want to handle the form submission. Let's update the code as follows:

<form method="POST" action="tasks">
   <input type="text" id="title">
   <button type="submit">save</button>
</form>
Enter fullscreen mode Exit fullscreen mode

I add just add some styles and here is the result:

Image description

If we try to submit the form now, we’ll encounter an error indicating that there is no route defined to handle this request, which is expected. To fix this, let’s go to the web.php file and define a new route for handling POST requests:

Route::get('/', [TaskController::class, 'index'])->name('tasks.all');

Route::view('/new-task', 'tasks.new');

Route::post('/tasks', [TaskController::class, 'store'])->name('tasks.create');
Enter fullscreen mode Exit fullscreen mode

Now, let’s define the store function inside the controller to handle the form submission. The question is, how do we retrieve the data sent by the form?

Laravel provides a helper function called request that allows us to access the submitted data.

To verify if the process is working correctly, we can use another commonly helper function called dd (short for "Dump and Die"). This function will display the input it receives in the browser and stop the program execution at that point.

By using the dd function, we can inspect the submitted data and ensure that everything is functioning as expected. Let’s see the above output:

Image description

What just happened? What? 🤯🤯

The error occurred because of a security feature in Laravel called CSRF (cross-site request forgery) protection. This feature is designed to prevent CSRF attacks. I’ll explain more about this feature, known as middleware, later on. For now, all you need to know is that Laravel checks for a token in every POST request sent to the server to prevent CSRF attacks. If the token is not present or invalid, the request is rejected.

To address this issue, you can simply add @csrf to your form. When you refresh the page, Laravel automatically adds a hidden input tag to your form containing the necessary token. This code is specifically generated by Laravel for this form.

Now, if you enter some text in the form and click the “add” button again, the server will validate your request and display the text in the output.

Image description

Fix Page Expired in Iframe (optional)

This particular part of the tutorial might be a bit confusing and seems to be slightly outside the main focus of the series. However, if you’ve noticed, in the previous tutorials, I utilized a simple browser within VSCode. You can install any browser extension or set it up from here. But here’s the catch: most of these browsers display our webpage inside an iframe, essentially embedding our site.

To address this, in the context of development, you need to inform Laravel that for testing purposes, you can set the “same_site” attribute of sessions to “none” inside config/sessions and set “SESSION_SECURE_COOKIE” to “true” in the .env file. This will allow Laravel to ignore the embeding situation. However, please be aware that this setup in production enables others to embed your site’s pages on their own websites, which can pose a security risk:

Image description

As you can see in the image above, I am able to make a POST request with this configuration

Also I have included my VSCode settings within the project repo. with this setting you can easily open it up in inside browser by simply pressing the Alt+Shift+Backspace shortcut. You don’t need to install any additional packages in your VSCode!

Let’s complete the store function.

In the previous tutorial, we used Tinker to save a record. We’ll do the same here and save the task submitted through the form into the table:

Image description

Congratulations! In this tutorial you just learn how to send successfully secure request with CSRF protection to the server and saved a record in the database based on that request. In the next tutorial, we’ll cover how to validate user input before storing it in the database.

Top comments (0)