How to insert data into MySQL database using Laravel 11
To insert data into a MySQL database using Laravel 11, you have to follow the below steps:
Minimum requirement: PHP 8.2 or higher is needed to run Laravel 11.
Step 1: Create a database
create databse userdb
Step 2: Create the MySQL table (tblusers)
Table structure for table tblusers
CREATE TABLE tblusers (
id int(11) NOT NULL,
firstName varchar(255) DEFAULT NULL,
lastName varchar(255) DEFAULT NULL,
emailId varchar(255) DEFAULT NULL,
mobileNumber bigint(11) DEFAULT NULL,
address varchar(255) DEFAULT NULL,
state varchar(255) DEFAULT NULL,
city varchar(255) DEFAULT NULL,
postingDate timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
Step 3: Set Up Your Environment
Make sure your MySQL database is properly configured. In your .env file, configure the database connection:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password
Step 4: Create a blade file (resources/views/form.blade.php)
<html>
<head>
<title></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<style>
body {
background: #fafbfb;
}
/* FOOTER STYLES
–––––––––––––––––––––––––––––––––––––––––––––––––– */
.page-footer {
position: fixed;
right: 0;
bottom: 50px;
display: flex;
align-items: center;
padding: 5px;
z-index: 1;
}
.page-footer a {
display: flex;
margin-left: 4px;
}</style>
</head>
<body>
<div class="container my-5">
<div class="row justify-content-center">
<div class="col-lg-9">
<h1 class="mb-3">Register with us</h1>
<hr />
@if(session('success'))
<div class="alert alert-success">{{ session('success') }}</div>
@endif
@if(session('error'))
<div class="alert alert-danger">{{ session('error') }}</div>
@endif
<form method="post" action="{{ route('insertdata') }}">
@csrf
<div class="row g-3">
<div class="col-md-6">
<label for="your-name" class="form-label">First Name</label>
<input type="text" class="form-control" id="firstName" name="firstName" value="{{ old('firstName') }}">
<span class="text-danger">
@error('firstName')
{{ $message }}
@enderror
</span>
</div>
<div class="col-md-6">
<label for="your-surname" class="form-label">Last Name</label>
<input type="text" class="form-control" id="lastName" name="lastName" value="{{ old('lastName') }}">
<span class="text-danger">
@error('lastName')
{{ $message }}
@enderror
</span>
</div>
<div class="col-md-6">
<label for="your-email" class="form-label"> Email ID</label>
<input type="email" class="form-control" id="emailId" name="emailId" value="{{ old('emailId') }}">
<span class="text-danger">
@error('emailId')
{{ $message }}
@enderror
</span>
</div>
<div class="col-md-6">
<label for="your-subject" class="form-label">Mobile No</label>
<input type="text" class="form-control" id="mobileNumber" name="mobileNumber" value="{{ old('mobileNumber') }}">
<span class="text-danger">
@error('mobileNumber')
{{ $message }}
@enderror
</span>
</div>
<div class="col-12">
<label for="your-message" class="form-label">Address</label>
<textarea class="form-control" id="address" name="address" rows="5" > {{ old('address') }}</textarea>
<span class="text-danger">
@error('address')
{{ $message }}
@enderror
</span>
</div>
<div class="col-md-6">
<label for="your-email" class="form-label"> City</label>
<input type="text" class="form-control" id="city" name="city" value="{{ old('city') }}">
<span class="text-danger">
@error('city')
{{ $message }}
@enderror
</span>
</div>
<div class="col-md-6">
<label for="your-subject" class="form-label">State</label>
<input type="text" class="form-control" id="state" name="state" value="{{ old('state') }}">
<span class="text-danger">
@error('state')
{{ $message }}
@enderror
</span>
</div>
<div class="col-12">
<div class="row">
<div class="col-md-6">
<button type="submit" class="btn btn-dark w-100 fw-bold" name="submit" >Submit</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Step 5: Create a Model and Migration
Create a model that will correspond to the database table you want to insert data into. You can do this using the artisan command:
php artisan make:model your_ModelName
//for this tutorial
php artisan make:model UserInsert
You define the table name and fields that are mass assignable (e.g., firstname, LastName, emailId) in this model.
<?php
namespace App\Models\model;
use Illuminate\Database\Eloquent\Model;
class UserInsert extends Model
{
protected $table = 'tblusers';
public $timestamps = false;
protected $fillable = [
'firstName', 'lastName','emailId', 'mobileNumber','address','state','city'
];
}
Step 6: Create a controller for handling user inputs and insert the data into the database.
php artisan make:controller your_contollername
//For this tutorial
php artisan make:controller insertController
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
Use App\Models\UserInsert;
class insertController extends Controller
{
public function insertdata(Request $request){
$request->validate([
'firstName' => 'required',
'lastName' => 'required',
'emailId' => 'required',
'mobileNumber' => 'required|numeric|digits:10',
'address' => 'required',
'state' => 'required',
'city' => 'required'
]);
$user=DB::table('tblusers')
->insert([
'firstName' => $request->firstName,
'lastName' => $request->lastName,
'emailId' => $request->emailId,
'mobileNumber' => $request->mobileNumber,
'address' => $request->address,
'state' => $request->state,
'city' => $request->city
]);
if($user){
return redirect()->route('form')->with('success', 'Data inserted successfully.');
} else{
return redirect()->route('form')->with('error', 'Something went wrong . Please Try again.');
}
}
}
Step7: Add a Route to Handle the Form Submission
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\insertController;
// For form
Route::get('/', function () {
return view('form');
})->name('form');
// For Form Submission
Route::post('/insertdata',[insertController::class,'insertdata'])->name('insertdata');
How to run the Script
1. Download the project zip file
2. Extract the file and copy insert-app folder
3. Paste inside root directory (for xampp xampp/htdocs, for wamp wamp/www, for lamp var/www/Html)
4.Open PHPMyAdmin (http://localhost/phpmyadmin)
5. Create a database with the name userdb
6. Import userdb.sql file(given inside the zip package in SQL file folder)
7. Run these command
PS C :\> cd xampp/htdocs/insert-app
PS C:\xampp\htdocs\insert-app> php artisan serve
8. After that open the browser run the script
