In this tutorial, you will learn how to insert data into database in laravel using Eloquent model.
So guys, to insert data into database in laravel 8 using Eloquent model, we will be creating model, migration and controller to insert data in laravel. Let's get started.
Step 1: Create a Model and Migration by following command:
$ php artisan make:model Student -m
Model: Lets open Student Model in following path: app/Model/Student.php
<?php
namespaceApp\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
classStudentextendsModel
{
useHasFactory;
protected$table = 'students';
protected$fillable = [
'name',
'email',
'course',
'section',
];
}
Migration:Lets open create_students_table.php Migration table in following path:database/migrations/2021_05_30_create_students_table.php: (ADD this in your migration table)
publicfunctionup()
{
Schema::create('students', function (Blueprint$table) {
$table->id();
$table->string('name');
$table->string('email');
$table->string('course');
$table->string('section');
$table->timestamps();
});
}
Now lets migrate this students table into our database by following command:
$ php artisan migrate
Step 2: Go to web.php file in the following path as: routes/web.php and create a route (url) as follows: