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
1 |
create databse userdb |
Step 2: Create the MySQL table (tblusers)
Table structure for table tblusers
1 2 3 4 5 6 7 8 9 10 11 |
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:
1 2 3 4 5 6 |
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)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 |
<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:
1 2 3 4 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?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.
1 2 3 |
php artisan make:controller your_contollername //For this tutorial php artisan make:controller insertController |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?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
1 2 3 4 5 6 7 8 9 10 11 |
<?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