Form basic input Laravel 8 CRUD

Form basic input Laravel 8 CRUD

1. Create Migration for the Form Data

First, let's create a migration for the data you will store in the database. We will create a table for employee records that include fields like empname, phone, and department.

Run the following command to create a migration:

php artisan make:migration create_employee_records_table --create=employee_records

This will create a new migration file in database/migrations/. Open that file and define the table schema:

Migration File (database/migrations/xxxx_xx_xx_create_employee_records_table.php):

<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateEmployeeRecordsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('employee_records', function (Blueprint $table) { $table->id(); $table->string('empname'); $table->string('phone'); $table->string('department'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('employee_records'); } }

2. Run Migration

Once the migration is ready, run the following command to create the employee_records table in your database:

php artisan migrate

3. Create Model for EmployeeRecord

Now, let's create a model that corresponds to the employee_records table.

Run the following command:

php artisan make:model EmployeeRecord

This will create a model file in app/Models/EmployeeRecord.php. Open it and ensure it looks like this:

Model File (app/Models/EmployeeRecord.php):

<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class EmployeeRecord extends Model { use HasFactory; protected $fillable = [ 'empname', 'phone', 'department', ]; }

This model will allow you to interact with the employee_records table.

4. Controller to Handle the Form

Now, let's create a controller that will handle the form display and form submission.

Run the following command to create the controller:

php artisan make:controller FormController

Then, define the index method to show the form and the saveRecord method to process the form data.

Controller File (app/Http/Controllers/FormController.php):

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\EmployeeRecord; class FormController extends Controller { // Display the form public function index() { return view('form'); } // Save form data public function saveRecord(Request $request) { // Validate incoming data $validated = $request->validate([ 'empname.*' => 'required|string|max:255', 'phone.*' => 'required|string|max:20', 'department.*' => 'required|string', ]); // Save the records to the database foreach ($request->empname as $key => $empname) { EmployeeRecord::create([ 'empname' => $empname, 'phone' => $request->phone[$key], 'department' => $request->department[$key], ]); } // Redirect with success message return redirect()->back()->with('success', 'Employee records saved successfully!'); } }

Explanation of saveRecord method:

  • Validation: The form data is validated using the validate method. This ensures that the empname, phone, and department fields are required, and their lengths are restricted.

  • Saving Data: After validation, each employee record is saved into the employee_records table. The loop goes through each employee and inserts the corresponding data.

  • Redirect: After saving the data, it redirects the user back with a success message using session()->flash.

5. Update Web Routes

In your routes/web.php ,Define the routes to display and handle the form submission:

Web Routes (routes/web.php):

use App\Http\Controllers\FormController; Route::get('form', [FormController::class, 'index'])->name('form'); Route::post('form', [FormController::class, 'saveRecord'])->name('form.save');

This way, the form will show when you visit /form and the form will be submitted to the same route via a POST request.

6. Create the Blade View for the Form

Now, let's create the form view where users can input the employee records.

Blade File (resources/views/form.blade.php):

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Employee Form</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container mt-5"> <h2>Employee Records</h2> @if(session('success')) <div class="alert alert-success">{{ session('success') }}</div> @endif <form action="{{ route('form.save') }}" method="POST"> @csrf <div id="employee-fields"> <div class="employee-row mb-3"> <input type="text" name="empname[]" class="form-control mb-2" placeholder="Employee Name" required> <input type="text" name="phone[]" class="form-control mb-2" placeholder="Phone Number" required> <input type="text" name="department[]" class="form-control mb-2" placeholder="Department" required> <button type="button" class="btn btn-danger remove-row">Remove</button> </div> </div> <button type="button" class="btn btn-success" id="add-row">Add Employee</button> <button type="submit" class="btn btn-primary mt-3">Save Records</button> </form> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function () { // Add new row $('#add-row').click(function () { $('#employee-fields').append(` <div class="employee-row mb-3"> <input type="text" name="empname[]" class="form-control mb-2" placeholder="Employee Name" required> <input type="text" name="phone[]" class="form-control mb-2" placeholder="Phone Number" required> <input type="text" name="department[]" class="form-control mb-2" placeholder="Department" required> <button type="button" class="btn btn-danger remove-row">Remove</button> </div> `); }); // Remove row $(document).on('click', '.remove-row', function () { $(this).closest('.employee-row').remove(); }); }); </script> </body> </html>

Explanation of Blade View:

  • Success Message: If there's a success message in the session (from session()->flash()), it will be displayed in a green alert box.

  • Dynamic Rows: The #add-row button lets users add multiple employee rows. Each row contains fields for the employee's name, phone number, and department.

  • Remove Row: The remove-row button allows users to remove a row if they no longer want to include that employee.

7. Final Step: Run the Application

Now that everything is set up, run your Laravel app:

php artisan serve

Visit http://localhost:8000/form to see your form in action. Add multiple employee records, submit the form, and verify that the records are saved to the database.

Your Laravel Form is Ready!

You have successfully:

  1. Created a form to input employee records.

  2. Validated the data before saving it.

  3. Saved the data to the database.

  4. Displayed a success message after form submission.

  5. Click to Download

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close