How to Insert Data in Laravel | websolutioncode.com
How to Insert Data in Laravel | websolutioncode.com

How to Insert Data in Laravel

Introduction:

Laravel, a popular PHP framework, simplifies the process of building web applications with its elegant syntax and robust features. One essential aspect of web development is inserting data into a database. In this article, we will explore how to insert data into a database using Laravel, providing a step-by-step guide along with practical code examples.

Prerequisites:

Before we begin, ensure that you have Laravel installed on your machine. You can install Laravel using Composer by running the following command in your terminal:

composer create-project --prefer-dist laravel/laravel YourProjectName

Once the installation is complete, navigate to your project directory:

Database Setup:

Before inserting data, let’s set up a database. Open the .env file in your project root and configure the database connection settings. Modify the following lines with your database credentials:

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

Now, create a migration to define the structure of the table. Run the following command in your terminal:

php artisan make:migration create_example_table --create=examples

Open the generated migration file (located in the database/migrations directory) and define the columns you want in your table. For example:

// database/migrations/xxxx_xx_xx_create_example_table.php

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

class CreateExampleTable extends Migration
{
    public function up()
    {
        Schema::create('examples', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('description');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('examples');
    }
}

Run the migration to create the table:

php artisan migrate

Inserting Data:

Now, let’s create a controller and a form to Insert Data in Laravel into the database.

Create a controller:

php artisan make:controller ExampleController

Open the generated controller (located in the app/Http/Controllers directory) and add the following methods:

// app/Http/Controllers/ExampleController.php

use App\Models\Example;

class ExampleController extends Controller
{
    public function create()
    {
        return view('examples.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'required|string',
        ]);

        Example::create($data);

        return redirect()->route('examples.create')->with('success', 'Data inserted successfully!');
    }
}

Create a form view:

Create a new Blade view file named create.blade.php in the resources/views/examples directory:

<!-- resources/views/examples/create.blade.php -->

@extends('layouts.app')

@section('content')
    <div class="container">
        <h2>Create Example</h2>

        @if(session('success'))
            <div class="alert alert-success">{{ session('success') }}</div>
        @endif

        <form action="{{ route('examples.store') }}" method="POST">
            @csrf
            <div class="form-group">
                <label for="name">Name:</label>
                <input type="text" name="name" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="description">Description:</label>
                <textarea name="description" class="form-control" required></textarea>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>
@endsection

Define routes:

Open the routes/web.php file and add the following routes:

// routes/web.php

use App\Http\Controllers\ExampleController;

Route::get('examples/create', [ExampleController::class, 'create'])->name('examples.create');
Route::post('examples', [ExampleController::class, 'store'])->name('examples.store');

Conclusion:

With these steps, you have successfully set up a Laravel project, configured a database, created a migration, and implemented a controller and view for inserting data. This example provides a solid foundation for understanding the process of inserting data in Laravel, which you can extend for more complex applications.

Check our tools website Word count
Check our tools website check More tutorial

Leave a Reply