Storing Form Data in a Laravel Database: Step-by-Step Guide

When developing web applications with Laravel, a common task is to store form data in a database. In this tutorial, I’ll guide you through the process of capturing user input from a Laravel form and storing it in a database using Laravel’s powerful ORM, Eloquent.

Let’s get started!

Step 1: Setting Up the Database

Before diving into form submission, ensure that you have a database connection configured correctly in your Laravel application. Open the .env file and verify the database credentials (e.g., DB_CONNECTION, DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, DB_PASSWORD). If needed, make any necessary adjustments to match your database configuration. The.env file should look similar to the one below.




Step 2: Creating a Migration

We will now create a migration that will contain the definition of the structure of our database table. Run the following command to instruct Laravel to generate it:

php artisan make:migration create_user_comments_table
The Output of Artisan When Creating Our Migration

Laravel has now added a basic migration file to the folder database\migrations, which we can edit to suit our requirements.

Step 3: Editing the Migration

Now open the newly generated migration file and define the table schema within the up method. Here you can specify the columns you need to store your form data. In our example, we’ll make a form with fields like name, email, and message, so our migration file might look like this:


use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
     * Run the migrations.
    public function up(): void
        Schema::create('user_comments', function (Blueprint $table) {

     * Reverse the migrations.
    public function down(): void

Step 4: Running the Migration

To create the table in the database, run the migration using the following command:

php artisan migrate

This command will execute all pending migrations in order of creation date. In the example shown you can see Laravel first runs its 4 default migrations and then runs our newly added migration which creates the table user_comments:

The Output of Artisan When Running Our Migration

Step 5: Creating a Model

Next, run the following command to create a model UserComment that represents the table you just created:

php artisan make:model UserComment
The Output of Artisan When Creating Our Model: UserComment

Step 6: Creating Form in Blade

Now create a blade file in your /resources/views folder and copy and paste the code below to add the HTML code of the form.

<form action="{{ route('') }}" method="post">
            <td><input type="text" name="name" value=""></td>
            <td><input type="text" name="email" value=""></td>
            <td><textarea name="message"></textarea></td>
                <input type="submit" />

Note that we used a named route: “”, we’ll define this later in our routes/web.php

Step 7: Creating a Controller

Next, run the following artisan command to make a controller named CommentController:

php artisan make:controller CommentController
The Output of Artisan When Adding Our Controller: CommentController

Step 8: Creating the Routes

Now we will add 2 routes. We will name the first route “comment.index”, this will display our page containing the form. The other route will be named “”, this will receive the form and store it in the database.

Open your web.php file and add the following code:


use Illuminate\Support\Facades\Route;

Route::get('/comment', [App\Http\Controllers\CommentController::class, 'index'])->name('comment.index');
Route::post('/comment', [App\Http\Controllers\CommentController::class, 'store'])->name('');

This will indicate that Laravel should:

  • expect a GET to URL “/comment" and needs to call the function “index” in CommentController
  • expect a POST to URL “/comment" and needs to call the function “store” in CommentController

Step 9: Showing the Form

Now edit the CommentController and add a function called index by pasting the code below:


namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CommentController extends Controller
    public function index()
        return view('comment');

You should now be able to see the comment form when you open your browser:

Browser Showing Our User Comment Form

Step 10: Processing Form Data

We will now make changes to our CommentController by adding a store() function to handle the (post) form submission defined in our web.php route file. Within this function, we will create a new instance of the UserComment model and assign the input values from the form to the respective model attributes: name, email, and message.

Note that we have also added some validation rules which Laravel will check. This way we can ensure that the entered form fields contain the expected data.


namespace App\Http\Controllers;

use App\Models\UserComment;
use Illuminate\Http\Request;

class CommentController extends Controller
    public function index()
        return view('comment');

    public function store(Request $request)
            'name' => 'required|max:32',
            'email' => 'required|email',
            'message' => 'required|string|required|max:255'
        $userComment = new UserComment();
        $userComment->name = $request->input('name');
        $userComment->email = $request->input('email');
        $userComment->message = $request->input('message');

        // Additional logic or redirection after successful data storage

        return redirect()->back()->with('success', 'Comment stored successfully!');

Step 11: Displaying Feedback to the User

To ensure proper user feedback in cases of incomplete or invalid input, as well as after successfully storing the data, it’s important to provide informative messages.

When redirecting back to the form page, we can use the ->with() function to set a success message. Additionally, if there are any validation errors, Laravel will populate an $errors variable with the corresponding error messages.

To ensure that both the success message and validation errors are displayed when applicable, we need to include the following code snippet just above the comment form in your view file:

        {{ session()->get('success') }}

@if ($errors->any())
        @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>

Now, when attempting to save the form with missing or invalid inputs, we will encounter validation errors:

Screenshot of Comment Form With Validation Error Messages

However, if we fill in valid values and resubmit the form, the input will be successfully saved:

Screenshot of Comment Form Filled in by a User

After saving the form, the browser will automatically redirect back to the form page and display a success message:

Screenshot of Comment Form With a Success Message

Now, if you view the database you can see the data has been stored correctly. You might use a tool like phpMyAdmin, or my personal favorite the free MySQL tool: HeidiSQL which will show:

Our Stored Form Data in the Database as Shown in HeidiSQL

Further reading

We can further improve and shorten our Controller code by using the following steps:

  1. Moving the validation rules into a Form Request Class
  2. Enable Mass Assign of values on the properties in the Model UserComment (name, email, message)
  3. Call Eloquent create method and mass assign the values of all validated fields.
public function store(UserCommentStoreRequest $request)
    return redirect()->back()->with('success', 'Comment stored successfully!');

To learn exactly how to apply Mass Assignment and a Form Request to achieve this read our detailed guide: Why Use Laravel Form Request and How? (BIG Code improvement)


In this tutorial, we explored how to build a Laravel application that stores form data into a database using.

By following the steps outlined, you’ve learned how to capture and validate user input using a form and store it in a database using an Eloquent model.

Enjoy adding these techniques in your own applications. Happy Coding!

Johan van den Broek

Johan is the creator of As a child, he began tinkering with various programming languages, many of which have been long forgotten today. Currently, he works exclusively with PHP and Laravel, and his passion for programming remains to this day.

2 thoughts on “Storing Form Data in a Laravel Database: Step-by-Step Guide

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts