# Store form input in the database with Laravel

> Learn how to build a Laravel form that stores user input in the database using an Eloquent model, a controller, routes, and a Blade view to display it.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2023-06-15 | Topics: [Laravel](https://flaviocopes.com/tags/laravel/) | Canonical: https://flaviocopes.com/using-forms-to-accept-user-input-and-store-it-into-the-database/

Now we’re going to create a form to add dogs to the table.

To do so, first we create a **Dog model.**

What’s a model? A model is a class that allows us to interact with data stored in the database.

Each model represents a specific table in the database, and we use it to create, read, update and delete records.

Create the model from the terminal with this command:

```php
php artisan make:model Dog
```

![Terminal output showing Model app/Models/Dog.php created successfully after running php artisan make:model Dog command](https://flaviocopes.com/images/using-forms-to-accept-user-input-and-store-it-into-the-database/1.webp)

This creates a model in `app/Models/Dog.php`:

![VS Code editor showing the Dog.php model file with namespace, use statements and Dog class extending Model with HasFactory trait](https://flaviocopes.com/images/using-forms-to-accept-user-input-and-store-it-into-the-database/2.webp)

Notice the class inclues some classes under a “Eloquent” folder.

Eloquent is an **ORM** (object-relational mapper), a tool that basically lets us interact with a database using a (PHP, in this case) class.

The model has a corresponding table, which we do not mention, but it’s the `dogs` table we created beforehand because of the naming convention `dogs` table → `Dog` model.

We’re going to use this model to add an entry to the database.

We’ll show the user a form and they can add a dog name, and click “Add” and the dog will be added to the database.

First we add the `name` field we added to the table to an array named `$fillable`:

```php
protected $fillable = ['name'];
```

Like this:

```php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Dog extends Model
{
    use HasFactory;
		protected $fillable = ['name'];
}
```

A model is a **resource**, and once you define a model you’ll later be able to create a new resource, delete, update it.

Now let’s build a form to add a new dog to the database. 

Let’s add a new entry to `routes/web.php`

```php
Route::get('/newdog', function () {
    return view('newdog');
});
```

We create a controller named `DogController`:

```php
php artisan make:controller DogController
```

Laravel adds a `DogController.php` file into the folder `app/Http/Controllers/`

What is a controller? A controller takes an _action_ and determines what to do. 

For example we’ll create a form that sends a POST request to the `/dogs` route. 

The router will say “this controller is in charge” and will tell us which method to use. 

Inside the controller we write methods that perform actions, like adding data to the database, or updating it.

If you’re unsure what is a POST request, check my [HTTP tutorial](https://flaviocopes.com/http/).

We will start by adding a `create` method to the controller to handle the data coming from the form, so we can store that to the database.

Before doing so, in `routes/web.php` we add the `POST /dogs` route handle controller and we assign it the name `dog.create`

We also add a `/dogs` route which we call `dogs`. We now render the `dogs` view in it, which we have to create yet:

```php
use App\Http\Controllers\DogController;

//...

Route::post(
    '/dogs',
    [DogController::class, 'create']
)->name('dog.create');

Route::get('/dogs', function () {
    return view('dogs');
})->name('dogs');
```

![VS Code showing routes/web.php file with route definitions including GET /newdog, POST /dogs, and GET /dogs routes](https://flaviocopes.com/images/using-forms-to-accept-user-input-and-store-it-into-the-database/3.webp)

In `resources/views/` create a `newdog.blade.php` file, which contains a form whose **action** attribute points to the `dog.create` route:

```php
<form method="post" action="{{ route('dog.create') }}">
    @csrf
    <label>Name</label>
    <input type="text" name="name" id="name">
    <input type="submit" name="send" value="Submit">
</form>
```

Run `php artisan serve` if you stopped the service, and go to [http://127.0.0.1:8000/newdog](http://127.0.0.1:8000/newdog)

The style is not brilliant, but the form shows up:

![Browser showing a simple HTML form with Name input field and Submit button at localhost:8000/newdog](https://flaviocopes.com/images/using-forms-to-accept-user-input-and-store-it-into-the-database/4.webp)

Now back to the `app/Http/Controllers/DogController.php` file.

Inside the class we import the Dog model, and we add the `create` method which will first validate the form, then store the dog into the database.

Finally we redirect to the `index` route:

```php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Dog;

class NewDogFormController extends Controller
{
    public function create(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
        ]);
        Dog::create($request->all());

        return to_route('index');
    }
}
```

Now back to the form, enter a name and click “Submit”:

![Browser form with Roger typed in the name field, showing user input before submitting the form](https://flaviocopes.com/images/using-forms-to-accept-user-input-and-store-it-into-the-database/5.webp)

You will be redirected to `/dogs`, after the new dog was saved to the database.

![Database management interface showing dogs table with Roger entry saved with id 1, name Roger, and timestamps](https://flaviocopes.com/images/using-forms-to-accept-user-input-and-store-it-into-the-database/6.webp)

In the browser there’s an error now but don’t worry - it’s because we haven’t added a `dogs` view yet.

![Laravel error page showing InvalidArgumentException with View dogs not found error message in browser](https://flaviocopes.com/images/using-forms-to-accept-user-input-and-store-it-into-the-database/7.webp)

In this view we’ll visualize the database data.

Create the file `resources/views/dogs.blade.php` and in there we’re going to loop over the `$dogs` array with Blade to display the data to the user:

```php
@foreach ($dogs as $dog)
    {{ $dog->name }}
@endforeach
```

This data does not come from nowhere. It must be passed to the template.

So in `routes/web.php` we now have

```php
Route::get('/dogs', function () {
    return view('dogs');
})->name('dogs');
```

and we have to first retrieve the data from the model, and pass it to the view.

First we import the model at the top of the file:

```php
use App\Models\Dog;
```

Then in the route we call `Dog::all();` to get all the dogs stored and we assign them to a `$dogs` variable which we pass to the template:

```php
Route::get('/dogs', function () {
    $dogs = Dog::all();
    return view('dogs', ['dogs' => $dogs]);
})->name('dogs');
```

Here’s the result:

![Browser displaying the dogs page at localhost:8000/dogs showing list of dog names Roger Syd Botolo Zoe retrieved from database](https://flaviocopes.com/images/using-forms-to-accept-user-input-and-store-it-into-the-database/8.webp)

![Database interface showing multiple dog records in the dogs table with 4 entries: Roger, Syd, Botolo, and Zoe with their timestamps](https://flaviocopes.com/images/using-forms-to-accept-user-input-and-store-it-into-the-database/9.webp)
