Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      May 31, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      May 31, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      May 31, 2025

      How To Prevent WordPress SQL Injection Attacks

      May 31, 2025

      Windows 11 version 25H2: Everything you need to know about Microsoft’s next OS release

      May 31, 2025

      Elden Ring Nightreign already has a duos Seamless Co-op mod from the creator of the beloved original, and it’ll be “expanded on in the future”

      May 31, 2025

      I love Elden Ring Nightreign’s weirdest boss — he bargains with you, heals you, and throws tantrums if you ruin his meditation

      May 31, 2025

      How to install SteamOS on ROG Ally and Legion Go Windows gaming handhelds

      May 31, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Oracle Fusion new Product Management Landing Page and AI (25B)

      May 31, 2025
      Recent

      Oracle Fusion new Product Management Landing Page and AI (25B)

      May 31, 2025

      Filament Is Now Running Natively on Mobile

      May 31, 2025

      How Remix is shaking things up

      May 30, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Windows 11 version 25H2: Everything you need to know about Microsoft’s next OS release

      May 31, 2025
      Recent

      Windows 11 version 25H2: Everything you need to know about Microsoft’s next OS release

      May 31, 2025

      Elden Ring Nightreign already has a duos Seamless Co-op mod from the creator of the beloved original, and it’ll be “expanded on in the future”

      May 31, 2025

      I love Elden Ring Nightreign’s weirdest boss — he bargains with you, heals you, and throws tantrums if you ruin his meditation

      May 31, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»How to insert data into MySQL database using Laravel 11

    How to insert data into MySQL database using Laravel 11

    January 29, 2025

    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 AppModelsmodel;
    use IlluminateDatabaseEloquentModel;
    
    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 AppHttpControllers;
    use IlluminateSupportFacadesDB;
    use IlluminateHttpRequest;
    Use AppModelsUserInsert;
    
    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 IlluminateSupportFacadesRoute;
    use AppHttpControllersinsertController;
    
    // 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

    Hostinger

    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:xampphtdocsinsert-app> php artisan serve

    8. After that open the browser run the script

    http://127.0.0.1:8000/

    Download Full source code(Insert Data Using Laravel11)
    Size: 27.4 MB
    Version: V 1.0
    Download Now!

    The post How to insert data into MySQL database using Laravel 11 appeared first on PHPGurukul.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleWindows 10 KB5050081 auto installs new Outlook web, direct download .msu with DAC fix
    Next Article 3 Questions: Modeling adversarial intelligence to exploit AI’s security vulnerabilities

    Related Posts

    Artificial Intelligence

    Markus Buehler receives 2025 Washington Award

    May 31, 2025
    Artificial Intelligence

    LWiAI Podcast #201 – GPT 4.5, Sonnet 3.7, Grok 3, Phi 4

    May 31, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    Distribution Release: Kali Linux 2025.1a

    News & Updates

    Twelve Labs Introduces Pegasus-1: A Multimodal Language Model Specialized in Video Content Understanding and Interaction through Natural Language

    Development

    Windows 10 Suddenly Takes Forever To Startup: 8 Tested Fixes

    Development

    Duplicati – store encrypted backups online

    Linux

    Highlights

    Artificial Intelligence

    Need a research hypothesis? Ask AI.

    December 20, 2024

    Crafting a unique and promising research hypothesis is a fundamental skill for any scientist. It…

    IMSProg – I2C, SPI and Microwire EEPROM/Flash chip programmer

    April 23, 2025

    How to Benchmark Your Code in C#

    November 19, 2024

    Your guide to generative AI and ML at AWS re:Invent 2024

    November 19, 2024
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.