Insert Form data into database using laravel

In this tutorial, You will learn how to insert form data into database using laravel. In Laravel, you can insert data into the database using two primary approaches: Eloquent ORM (Object-Relational Mapping) or the Query Builder.

Eloquent is Laravel’s built-in ORM that allows you to interact with your database using an object-oriented syntax that is simple & standard way to use for creating data  So, Let’s start to insert data using  Eloquent ORM.

insert Form Data into Database in Laravel 10

1. Create a Laravel Project

Before starting, you’ll need to create a new Laravel project.To create a new Laravel project, you can use the following command in your terminal or command prompt

composer create-project --prefer-dist laravel/laravel your-project-name

This command will download the latest version of Laravel and set up a new project for you.

2. Create a new database

you can’t create database through Laravel’s Artisan command directly. Instead, you usually create the database using a database management tool (like MySQL or the command line), and then you configure Laravel to use that database.

i. Configure laravel database

Open the .env file in your Laravel project root directory and configure the database connection settings

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_user
DB_PASSWORD=your_database_password

Make sure the DB_DATABASE value matches the name of the database you created.

3. Create a Migration:

Create a new migration table using the Artisan command.Open your terminal and run the following  command to generate a migration file

php artisan make:migration create_students_table

This will create a new migration file in the database/migrations directory.

Open the generated migration file create_students_table.php. Add the columns “name,” “city,” and “marks” to the up method like

Migration File: create_students_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('city');
            $table->bigInteger('marks');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('students');
    }
};

4. Run the Migration

Run the migration to create the table in the database

php artisan migrate

5. Create a Model

Create a model using the Artisan command:

php artisan make:model Student

This will create a new model file in the app/Models directory.

Model File: Student.php

Open model file and define the table name and fillable fields:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    protected $table = 'students';
    protected $fillable = ['name', 'city', 'marks'];
}

6. Create a Controller

Create a controller using the Artisan command:

php artisan make:controller StudentController

This will create a new model file in the App\Http\Controllers directory.

Controller File: StudentController.php

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Student;

class StudentController extends Controller
{
    
    public function index()
    {
        $students=Student::all();
        return view('home');
    }

    public function create(Request $request)
    {
       // Create a new instance of the Student model
       $student = new Student;
       $student->name = $request->name;
       $student->city = $request->city;
       $student->marks = $request->marks;
       $student->save();
       return redirect(route('index'))->with('status', 'Student Added!');
    }
}

 

Assigning Request Data to Model Properties:

  • When a user submits a form with student information (like name, city, and marks), the submitted data is available in the $request object.
  • $student->name = $request->name; means we take the “name” value from the form (sent in the request) and assign it to the “name” property of the $student model.
  • Similarly, $student->city = $request->city; assigns the “city” value, and $student->marks = $request->marks; assigns the “marks” value.

Saving the Record to the Database:

  • After we’ve assigned the form data to the model properties, $student->save(); is like telling Laravel, “Hey, save this student record to the database.”
  • It’s like pressing the “save” button to permanently store the student’s information in the database

7. Create a View

In your resources/views directory, create a new Blade template file. Let’s name it home.blade.php.

View File: home.blade.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel Insert Data</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous">
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-sm-6">
                <form action ="" method="POST">
                    @csrf
                    <div class="mb-3">
                        <label for="name" class="form-label">Name</label>
                        <input type="text" class="form-control" id="name" name="name">
                    </div>
                    <div class="mb-3">
                        <label for="city" class="form-label">City</label>
                        <input type="text" class="form-control" id="city" name="city">
                    </div>
                    <div class="mb-3">
                        <label for="marks" class="form-label">Marks</label>
                        <input type="number" class="form-control" id="marks" name="marks">
                    </div>
                    <button type="submit" class="btn btn-success">Submit</button>
                </form>
                @if(session()->has('status'))
                <div class="alert alert-success mt-3">
                    {{ session('status') }}
                </div>
                @endif
            </div>
        </div>
    </div>
</body>
</html>

8. Create Routes

Let’s create a route in the web.php file

routes file- web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StudentController;

Route::get('/',[StudentController::class,'index'])->name('index');
Route::post('/',[StudentController::class,'create'])->name('create');

9. Run the Development Server

Open a terminal, navigate to your project directory, and run the following command to start the Laravel development server

php artisan serve

This will start the server, and you should see output indicating that the development server is running.Open your web browser and go to the provided URL:

http://127.0.0.1:8000/