Using Forms to Accept User Input and Store it into the Database
Tags: Laravel, programming, forms, database
This tutorial is part of the Laravel Handbook. Download it from here.
In this tutorial, we will learn how to create a form that accepts user input and stores it into the database using Laravel.
To begin, we need to create a Dog
model. A model allows us to interact with data stored in the database. Each model represents a specific table in the database and provides methods to perform database actions such as create, read, update, and delete records.
To create the Dog
model, open the terminal and run the following command:
1 | php artisan make:model Dog |
This command will generate a Dog.php
file in the app/Models
directory. The model is based on the Eloquent ORM (object-relational mapper), which allows us to interact with the database using PHP classes.
Next, open the Dog.php
file and add the name
field to the $fillable
array. This will allow us to mass assign the name
field when creating a new dog record:
1 |
|
Now that we have the model set up, let’s create a form to add a new dog to the database.
First, open the routes/web.php
file and add the following routes:
1 | use App\Http\Controllers\DogController; |
In the above code, we have defined two routes: /newdog
and /dogs
. The /newdog
route renders a view called newdog.blade.php
, which contains the form. The /dogs
route renders a view called dogs.blade.php
, which displays the dogs stored in the database.
Next, run the following command to generate a DogController
:
1 | php artisan make:controller DogController |
This will create a DogController.php
file in the app/Http/Controllers
directory. A controller is responsible for handling actions and performing actions based on the request.
Open the DogController.php
file and add the following code:
1 |
|
In the above code, the create
method handles the data submitted from the form. It validates the input and then creates a new Dog
record using the create
method of the Dog
model. Finally, it redirects the user to the /dogs
route.
Now, let’s create the newdog.blade.php
file in the resources/views
directory. This file will contain the form to add a new dog record:
1 | <form method="post" action="{{ route('dog.create') }}"> |
To view the form, run php artisan serve
and go to http://127.0.0.1:8000/newdog.
Once you submit the form, the data will be stored in the database and you will be redirected to the /dogs
route, which displays the dogs stored in the database.
To display the dogs in the dogs.blade.php
file, add the following code:
1 | @foreach ($dogs as $dog) |
Now, when you visit http://127.0.0.1:8000/dogs, you will see a list of dogs displayed on the page.
And that’s it! You have successfully created a form that accepts user input and stores it into the database using Laravel. Feel free to explore more about forms and database interactions in Laravel’s documentation.