I need to insert some data into a sqlite database, manually inside a (Laravel 5) controller and without a form.
I've tried with this methods:
1st:
DB::insert('insert into cars values (?, ?, ?)', [1, "Infinity", "MS500"]);
2nd:
Car::create([
'brand' => 'Infinity',
'model' => 'MS500',
]);
3rd:
$car = new Car();
$car->setAttribute('brand', 'Infinity');
$car->setAttribute('model', 'MS500');
$car->save();
The 1st method works, but I need to insert thousand of rows, and the time and performance is not so good.
The 2nd and 3rd methods give me this error:
Missing argument 2 for Illuminate\Database\Eloquent\Model::setAttribute(), called in /var/www/html/AppLaravel/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php on line 525 and defined
I don't know what means this error, I have found a lot about it, and about to populate the data into the database manually, with no results.
This is the model class:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Car extends Model
{
const CREATED_AT = null;
const UPDATED_AT = null;
protected $fillable = ['brand', 'model'];
}
This is the migration class:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCarsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('cars', function (Blueprint $table) {
$table->increments('id');
$table->string('brand');
$table->text('model');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('cars');
}
}
EDIT
I've tested with the bulk insertion too:
4th
$arr = [
[
'brand' => 'Infinity',
'model' => 'MS500',
],
[
'brand' => 'Toyota',
'model' => 'LK2500',
],
];
DB::insert($arr);
... but I got this new error:
ErrorException (E_NOTICE) Array to string conversion