Skip to content

Using forms to accept user input and store it into the database

New Course Coming Soon:

Get Really Good at Git

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 artisan make:model Dog

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

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:

protected $fillable = ['name'];

Like this:

<?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

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

We create a controller named DogController:

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.

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:

use App\Http\Controllers\DogController;

//...

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

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

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

<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

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

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

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”:

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

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

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:

@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

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:

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:

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

Here’s the result:

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my Laravel Handbook

Here is how can I help you: