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

      CodeSOD: Using the Old Bean

      June 19, 2025

      IBM launches new integration to help unify AI security and governance

      June 18, 2025

      Meet Accessible UX Research, A Brand-New Smashing Book

      June 18, 2025

      Modernizing your approach to governance, risk and compliance

      June 18, 2025

      RAIDOU Remastered: The Mystery of the Soulless Army Review (PC) – A well-done action-RPG remaster that makes me hopeful for more revivals of classic Atlus titles

      June 18, 2025

      With Windows 10 circling the drain, Windows 11 sees a long-overdue surge

      June 18, 2025

      This PC app boosts FPS in any game on any GPU for only $7 — and it just got a major update

      June 18, 2025

      Sam Altman claims Meta is trying to poach OpenAI staffers with $100 million bonuses, but “none of our best people have decided to take them up on that”

      June 18, 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

      Manipulate Image URLs in Laravel with the Image Transform Package

      June 19, 2025
      Recent

      Manipulate Image URLs in Laravel with the Image Transform Package

      June 19, 2025

      How cron and Task Scheduler work in Laravel

      June 19, 2025

      Laravel: Import Very Large CSV With Jobs and Queues

      June 19, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      FOSS Weekly #25.25: Nitrux Hyprland, Joplin Tips, Denmark Ditching Microsoft, Tiling Moves and More Linux Stuff

      June 19, 2025
      Recent

      FOSS Weekly #25.25: Nitrux Hyprland, Joplin Tips, Denmark Ditching Microsoft, Tiling Moves and More Linux Stuff

      June 19, 2025

      BrosTrend 5 Port 2.5GB Switch Review

      June 19, 2025

      Cuneo is a widget-like calculator and conversion tool

      June 19, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Laravel 11 CRUD Operation

    Laravel 11 CRUD Operation

    May 4, 2025

    In this tutorial, we will learn how to create a CRUD Operation using Laravel 11.

    Step 1: Install Laravel

    composer create-project laravel/laravel crud-app

    Step 2: 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=laravelcruddb
    DB_USERNAME=root
    DB_PASSWORD=

    Step 3: Create the MySQL table (users)

    Table structure for table users

    CREATE TABLE `users` (
      `id` int(11) NOT NULL,
      `firstName` varchar(255) DEFAULT NULL,
      `lastName` varchar(255) DEFAULT NULL,
      `emailId` varchar(255) DEFAULT NULL,
      `phoneNumber` bigint(12) DEFAULT NULL,
      `streetAddress` text DEFAULT NULL,
      `zipCode` int(11) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

    Step 4:Create a balde file for data insertion

    update.blade.php (resources/views/insert.blade.php)

    <div class="formbold-main-wrapper">
        <div class="formbold-form-wrapper">
    
          <form action="{{ route('adduser') }}" method="post">
            @csrf
            <div class="formbold-form-title">
              <h2 class="">Register now    ----------- <small>
                <a  href="{{ route('read') }}"> View Data</a>
            </small> </h2>
              <hr />
              <ul style="color:red; margin-top:2%" >
              @if($errors->all())
              @foreach ($errors->all() as $error) 
              <li>{{ $error }}</li>
              @endforeach
              @endif
              </ul>
    
            </div>
    
    
            <div class="formbold-input-flex">
              <div>
                <label for="firstname" class="formbold-form-label">
                  First name
                </label>
                <input
                  type="text"
                  name="firstname"
                  id="firstname"
                  value="{{ old('firstname') }}"
                  class="formbold-form-input  @error('firstname') is-invalid @enderror"
                />
              </div>
         
              <div>
                <label for="lastname" class="formbold-form-label"> Last name </label>
                <input
                  type="text"
                  name="lastname"
                  id="lastname"
                  class="formbold-form-input"
           
                /> 
              </div>
             
            </div>
      
            <div class="formbold-input-flex">
              <div>
                <label for="email" class="formbold-form-label"> Email </label>
                <input
                  type="email"
                  name="email"
                  id="email"
                  class="formbold-form-input"
                /> 
              </div>
    
         
              <div>
                <label for="phone" class="formbold-form-label"> Phone number </label>
                <input
                  type="text"
                  name="phone"
                  id="phone"
                  class="formbold-form-input"
                />
              </div>
            </div>
      
            <div class="formbold-mb-3">
              <label for="address" class="formbold-form-label">
                Street Address
              </label>
              <input
                type="text"
                name="address"
                id="address"
                class="formbold-form-input"
              />
            </div>
      
      
            <div class="formbold-input-flex">
              <div>
                <label for="post" class="formbold-form-label"> Post/Zip code </label>
                <input
                  type="text"
                  name="post"
                  id="post"
                  class="formbold-form-input"
                />
              </div>
        
            </div>
      
      
            <button class="formbold-btn" type="submit">Register Now</button>
          </form>
        </div>
      </div>
      <style>

    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:

    pphp artisan make:model your_ModelName
     
    //for this tutorial
    php artisan make:model user

    You define the table name and fields that are mass assignable (e.g., firstname, LastName, emailId) in this model.

    app/Models/Users.php

    <?php
    use IlluminateDatabaseMigrationsMigration;
    use IlluminateDatabaseSchemaBlueprint;
    use IlluminateSupportFacadesSchema;
    
    return new class extends Migration
    {
        /**
         * Run the migrations.
         */
        public function up(): void
        {
            Schema::create('users', function (Blueprint $table) {
                $table->id();
                $table->string('firstName',200);
                $table->string('lastName',200)->nullable();
                $table->string('emailId','200');
                $table->bigInteger('phoneNumber')->unsigned();
                $table->text('streetAddress');
                $table->integer('zipCode')->unsigned();
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         */
        public function down(): void
        {
            Schema::dropIfExists('users');
        }
    };

    Step 6: Create a controller for handling user inputs and insert/read/update/delete the data into the database.

    php artisan make:controller your_contollername
    //For this tutorial
    php artisan make:controller crudController

    app/Http/Controllers/crudController.php

    <?php
    
    namespace AppHttpControllers;
    use IlluminateHttpRequest;
    use IlluminateSupportFacadesDB;
    use AppHttpModelsUser;
    
    class crudController extends Controller
    {
        public function addUser(Request $request){
            $request->validate([
    'firstname' => 'required',
    'lastname' => 'required',
    'email' => 'required',
    'phone' => 'required|numeric',
    'address' => 'required',
    'post' => 'required'
    
            ]);
            $user=DB::table('users')
            ->insert([
                'firstName' => $request->firstname,
                'lastName' => $request->lastname,
                'emailId' => $request->email,
                'phoneNumber' => $request->phone,
                'streetAddress' => $request->address,
                'zipCode' => $request->post,
    
            ]);
      
            if($user){
                return redirect()->route('read')->with('success', 'Data inserted successfully.');
            } else{
                return redirect()->route('read')->with('error', 'Something went wrong . Please Try again.');
            }
        }
    }

    Step7: Add a Route to Handle the Form Submission

    <?php
    
    use AppHttpControllerscrudController;
    use IlluminateSupportFacadesRoute;
    
    Route::get('/', function () {
        return view('insert');
    });
    Route::controller(crudController::class)->group(function (){
        Route::post('/adduser','addUser')->name('adduser');
    });

    Step 8: We have already created crudController; now, we will add the function to show the inserted data in that controller.

    public function showUser(){
        $users=DB::table('users')
                     ->paginate(5);
        return view('read',['data' => $users]);
    }

    Step 9: Create a blade template to display/show data.

    update.blade.php (resources/views/read.blade.php)

    <div class="container-lg">
        <div class="table-responsive">
            <div class="table-wrapper">
                <div class="table-title">
                    <div class="row">
                        <div class="col-sm-8"><h2>User <b>Details</b></h2></div>
                        <div class="col-sm-4">
                            <a class="btn btn-info add-new" href="{{ route('insert') }}"><i class="fa fa-plus"></i> Add New</a>
                        </div>
                    </div>
                </div>
                @if(session('success'))
                <div class="alert alert-success">
               {{ session('success') }}
                  </div>
            @endif
    
            @if(session('error'))
            <div class="alert alert-danger">
         {{ session('error') }}
              </div>
        @endif
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>First Name</th>
                            <th>Last NAme</th>
                            <th width="200">Email id</th>
                            <th>Phone No</th>
                            <th>Address</th>
                            <th>Zip Code</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($data as $id => $user )
                            
                   
                        <tr>
                            <td>{{ $user->firstName }}</td>
                            <td>{{ $user->lastName }}</td>
                            <td>{{ $user->emailId }}</td>
                            <td>{{ $user->phoneNumber }}</td>
                            <td>{{ $user->streetAddress }}</td>
                            <td>{{ $user->zipCode }}</td>
                            <td>
                                <a class="add" title="Add" data-toggle="tooltip"><i class="material-icons"></i></a>
                                <a class="edit" title="Edit" data-toggle="tooltip" href="{{ route('update', $user->id) }}"><i class="material-icons"></i></a>
                                <a class="delete" title="Delete" data-toggle="tooltip" href="{{ route('delete', $user->id) }}"><i class="material-icons"></i></a>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
                <div class="mt-5">
                {{ $data->links() }}
                </div>
                <div class="mt-5">
                    Total Users: {{ $data->total()}}
                </div>
            </div>
        </div>
    </div>

    Step 10: Add the routes to the routes/web.php

    <?php
    
    use AppHttpControllerscrudController;
    use IlluminateSupportFacadesRoute;
    
    Route::get('/', function () {
        return view('insert');
    });
    Route::controller(crudController::class)->group(function (){
        Route::post('/adduser','addUser')->name('adduser');
        Route::get('/read','showUser')->name('read');
    });

    Step 11: Create the Edit View

    update.blade.php (resources/views/update.blade.php)

    <div class="formbold-form-wrapper">
     
          <form action="{{ route('updateuser', $data->id ) }}" method="post">
            @csrf
            <div class="formbold-form-title">
              <h2 class="">Update User Data</h2>
      
            </div>
            @if(session('success'))
            <div>{{ session('success') }}</div>
        @endif
            <div class="formbold-input-flex">
              <div>
                <label for="firstname" class="formbold-form-label">
                  First name
                </label>
                <input
                  type="text"
                  name="firstname"
                  id="firstname"
                  class="formbold-form-input"
                  value="{{ $data->firstName }}"
                />
              </div>
              <div>
                <label for="lastname" class="formbold-form-label"> Last name </label>
                <input
                  type="text"
                  name="lastname"
                  id="lastname"
                  class="formbold-form-input"
                  value="{{ $data->lastName }}"
                />
              </div>
            </div>
      
            <div class="formbold-input-flex">
              <div>
                <label for="email" class="formbold-form-label"> Email </label>
                <input
                  type="email"
                  name="email"
                  id="email"
                  class="formbold-form-input"
                  value="{{ $data->emailId }}"
                />
              </div>
              <div>
                <label for="phone" class="formbold-form-label"> Phone number </label>
                <input
                  type="text"
                  name="phone"
                  id="phone"
                  class="formbold-form-input"
                  value="{{ $data->phoneNumber }}"
                />
              </div>
            </div>
      
            <div class="formbold-mb-3">
              <label for="address" class="formbold-form-label">
                Street Address
              </label>
              <input
                type="text"
                name="address"
                id="address"
                class="formbold-form-input"
                value="{{ $data->streetAddress }}"
              />
            </div>
      
            <div class="formbold-input-flex">
              <div>
                <label for="post" class="formbold-form-label"> Post/Zip code </label>
                <input
                  type="text"
                  name="post"
                  id="post"
                  class="formbold-form-input"
                  value="{{ $data->zipCode }}"
                />
              </div>
    
            </div>
            <button class="formbold-btn" type="submit">Update</button>
          </form>
        </div>
      </div>

    Step 12: Create the function to fetch/read the particular user’s data in the crudController

    public function updatePage(string $id){
        //$users=DB::table('users')->where('id' , $id)->get();
        $users=DB::table('users')->find($id);
        return view('update',['data' => $users]);
    }

    Step 13: Create the function to update the particular user’s data in the crudController.

    public function updateUser(Request $request, $id){
       // return $request;
        $user=DB::table('users')
        ->where('id', $id)
        ->update([
            'firstName' => $request->firstname,
            'lastName' => $request->lastname,
            'emailId' => $request->email,
            'phoneNumber' => $request->phone,
            'streetAddress' => $request->address,
            'zipCode' => $request->post
    
        ]);
    
        if($user){
            return redirect()->route('read')->with('success', 'Data updated successfully.');
           // echo "<h2>Data Inserted Successfuly</h2>";
    
        } else{
            return redirect()->route('read')->with('error', 'Something went wrong . Please Try again.');
    
        }
    }

    Step 14: Define Routes for update.

    <?php
    use AppHttpControllerscrudController;
    use IlluminateSupportFacadesRoute;
    Route::get('/', function () {
        return view('insert');
    });
    Route::controller(crudController::class)->group(function (){
    
        Route::post('/adduser','addUser')->name('adduser');
        Route::get('/read','showUser')->name('read');
        Route::get('/update/{id}','updatePage')->name('update');
        Route::post('/updateuser/{id}','updateUser')->name('updateuser');
        Route::get('/delete/{id}','deleteUser')->name('delete');
    });

    Step 15: Create the function to delete the particular user’s data in the crudController.

    public function deleteUser(string $id){
        $user=DB::table('users')
        ->where('id', $id)
        ->delete();
        if($user){
            return redirect()->route('read')->with('success', 'Data deleted.');
           // echo "<h2>Data Inserted Successfuly</h2>";
    
        } else{
            echo "<h2>Something went wrong . Please Try again. </h2>";
        }
    }

    Step 16: Define Routes for deletion.

    public function deleteUser(string $id){
        $user=DB::table('users')
        ->where('id', $id)
        ->delete();
        if($user){
            return redirect()->route('read')->with('success', 'Data deleted.');
           // echo "<h2>Data Inserted Successfuly</h2>";
        } else{
            echo "<h2>Something went wrong . Please Try again. </h2>";
        }
    }

    How to run the Script

    1. Download the project zip file

    2. Extract the file and copy crud-app  folder

    3. Paste inside root directory (for xampp xampp/htdocs, for wamp wamp/www, for lamp var/www/Html)

    4. Run these commands

    PS C :> cd xampp/htdocs/crud-app

    PS C:xampphtdocscrud-app> php artisan migrate

    PS C:xampphtdocscrud-app> php artisan serve

    8. After that, open the browser and run the script

    http://127.0.0.1:8000/fetch


    Script Demo

    View Demo
    Laravel 11 CRUD Operation (Source Code)
    Size: 26.6 MB
    Version: V 1.0
    Download Now!

    The post Laravel 11 CRUD Operation appeared first on PHPGurukul.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleFCC clears Surface Laptop 13″, Pro 12″ with Snapdragon, rounded design
    Next Article New Xbox games launching this week, from May 5 through May 11 — Revenge of the Savage Planet hits Xbox Game Pass

    Related Posts

    Development

    Manipulate Image URLs in Laravel with the Image Transform Package

    June 19, 2025
    Development

    How cron and Task Scheduler work in Laravel

    June 19, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    The next chapter of our Gemini era

    Artificial Intelligence

    OThink-R1: A Dual-Mode Reasoning Framework to Cut Redundant Computation in LLMs

    Machine Learning

    I tested DJI’s latest flagship drone, and it’s straight from the future (with one caveat)

    News & Updates

    How to Code Linked Lists with TypeScript: A Handbook for Developers

    Development

    Highlights

    Rest Assured – Schema to use cannot be null

    May 30, 2025

    I’m working with Java and REST Assured to test REST APIs. I was trying the example with JSON schema validation but it throws this error:
    java.lang.IllegalArgumentException: Schema to use cannot be null

    at io.restassured.module.jsv.JsonSchemaValidator.validateSchemaIsNotNull(JsonSchemaValidator.java:270)
    at io.restassured.module.jsv.JsonSchemaValidator.access$300(JsonSchemaValidator.java:75)
    at io.restassured.module.jsv.JsonSchemaValidator$JsonSchemaValidatorFactory.create(JsonSchemaValidator.java:281)
    at io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchema(JsonSchemaValidator.java:166)
    at io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath(JsonSchemaValidator.java:117)
    at suites.SchemaFollowupTest.ContractFollowUpTestSuccess(SchemaFollowupTest.java:44)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

    My test code is:
    given()
    .header(“Content-Type”, ContentType.JSON)
    //.header(“Authorization”, “Bearer ” + ConfigEnvironments.TOKEN_K8S)
    .body(jsonBody)
    .when()
    .post(ConfigEnvironments.BASE_URL_CLAIMENGINE +”/api/v1/FollowUp”)
    .then().log().all()
    .statusCode(202)
    .and()
    .body(matchesJsonSchemaInClasspath(“src/test/resource/followup-schema.json”));

    My strucuture folder is here:
    [1]: https://i.sstatic.net/K9m2UjGy.png

    CVE-2025-27087 – Cray Operating System (COS) Kernel Local Denial of Service (DoS)

    April 22, 2025

    CVE-2025-40625 – TCMAN GIM Unauthenticated File Upload RCE

    May 6, 2025

    Life in Startup Pivot Hell with Ex-Microsoft Lonewolf Engineer Sam Crombie [Podcast #171]

    May 9, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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