When working with Laravel applications, we often need to store data in a database. Here we will discuss how to capture user data from a Laravel form and save in the database using Laravel’s powerful ORM, Eloquent. Let’s go through the main steps to do this process.
Store Form data in Database
Step 1: Set Up a Database
We need to first set up a database connection before storing user input in the database. Database credentials can be added in the .env file of your Laravel project. You can add database configurations in your .env file as shown below.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=root
DB_PASSWORD=pswd
Step 2: Create migration
Next, we will create a database migration to define the structure of the database table. You can run the command given below for this.
php artisan make:migration create_user_table
This adds a basic migration file under the database/migrations folder, where we can edit our migrations.
Step 3: Edit Migration
In this step, we will edit the newly created migration file to define a table schema inside the up function. We can specify the columns we need to save data. Let’s go through an example where we will create a form with name, email, and a message, as shown below.
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void {
Schema::create('user_comments', function (Blueprint $table) {
$table->id();
$table->string(‘name’);
$table->string(‘email’);
$table->string(‘message’);
$table->timestamps():
}
}
public function down(): void {
Schema::dropIfExists(‘user_table’);
}
Step 4: Run the migration
We can run the migration to create the database table, using the command below.
php artisan migrate
This will execute all pending migrations.
Step 5: Create a Model
Now, you can run the command below to create a new Model.
php artisan make:model UserModel
Step 6: Create a Form in Blade View
To get data input from a user, we will create a form in the blade view file under the resources/views
folder.
form action="{{ route('comment.store') }}" method="post">
@csrf
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name" value=""></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value=""></td>
</tr>
<tr>
<td>Message</td>
<td><textarea name="message"></textarea></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" />
</td>
</tr>
</table>
</form>
Step 7: Create a Controller
Next step we will make a new controller using the command below.
php artisan make:controller UserController
Step 8: Create New Route
This step we will create routes to display and save data from the form as shown below.
Route::get('/users, [App\Http\Controllers\CommentController::class, 'index'])->name(users.index');
Route::post('/users, [App\Http\Controllers\CommentController::class, 'store'])->name(users.store');
The routes above link the user blade with Controller functions ‘index’ and ‘store’ to get data from the blade view and save to the database.
Step 9: Show the Form
Next, in the UserController
, we can define the index function to return the users view blade as shown below.
public function index(){
return view(‘users.index’);
}
This will show an input form to the user to enter their details.
Step 10: Process User Data
Next we will add the store() method in the UserController
to store user data in the database. As shown below, we will first validate the data and then save in the database.
public function store(Request $request)
{
$request->validate([
'name' => 'required|max:32',
'email' => 'required|email',
'message' => 'required|string|required|max:255'
]);
$userData = new UserData();
$userData->name = $request->input('name');
$userData->email = $request->input('email');
$userData->message = $request->input('message');
$userData->save();
// Additional logic or redirection after successful data storage
return redirect()->back()->with('success', User data stored successfully!');
}
The above function will save data to the database table we created in the initial steps.
We can also display feedback messages to the user, if the data is stored or not. You can implement feedback messages as shown below.
@if(session()->has('success'))
<p>
{{ session()->get('success') }}
</p>
@endif
@if ($errors->any())
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
@endif
Hope the step-by-step tutorial will help you create forms in Laravel applications and save data in the database using Laravel’s ORM, Eloquent Model.