Laravel Insert Data using Create Method

In this example we learn how to insert data using create method in laravel. Also i explain easy way to create method and insert data in laravel. Create method to you can easy to pass array and insert data into database. Laravel create method accept only array, in this array we have pass key and value. Key is same as your datatable column name.

if you use create method in laravel at that time laravel required prottected $fillable in your laravel model.

Read Also :  Laravel 8 CRUD Operation With Ajax Example

Laravel Insert Data using Create Method

Step 1: Create Model

First you can create Demo model for use create method. Following command to you can create model and migration in laravel.

php artisan make:model Demo -m

Demo.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Demo extends Model
{
    use HasFactory;
    protected $fillable = ['name','email','username','password'];
}

Step 2: Create migration

In this step i create migration of demos table.

<?php

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

class CreateDemoTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('demo', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('username');
            $table->string('password');
            $table->timestamps();
        });  
    }

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

 

Step 3: Create Route

In this step i create route and use create method in laravel.

<?php

use Illuminate\Support\Facades\Route;

use App\Models\Demo;

 Route::get("insert_create", function(){
     Demo::create([
         'name' => 'London to Paris',
         'email' => 'London11@gmail.com',
         'username' => 'London to Paris',
         'password' => 'London to Paris',
     ]);
  });

I hope you understand create method in laravel….

Read Also :  How to Set Session Data In Laravel ?