How to insert data in database in laravel 5.8 and above
Step 1: Install your Laravel by issuing the Composer with the command called create-project command in your terminal:
$ composer create-project --prefer-dist laravel/laravel blog "5.8.*"
Step 2: Setup your database (DB) and set the credentials in your environment file (.env) in your installed laravel application.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database #do not use this symbol Hash (#) in database
DB_USERNAME=your_username #do not use this symbol Hash (#) in username
DB_PASSWORD=your_password #do not use this symbol Hash (#) in password
Step 3: Go to your application and open the folder by following:
app/Providers/AppServiceProvider.php, open this file and add the below code, to set the defaultStringLength to skip the Error called: Specified key was too long error.
use Illuminate\Support\Facades\Schema;
public function boot()
{
Schema::defaultStringLength(191);
}
Step 4: Now, we will create the migration to create a table named students in a laravel database with following command as follows:
After successfully table created. open the migration file in the following path: database/migrations/somedate2021_create_students_table.php and paste the below code:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
classCreateStudentsTableextendsMigration
{
/**
* Run the migrations.
*
* @returnvoid
*/
publicfunctionup()
{
Schema::create('students', function (Blueprint$table) {
$table->bigIncrements('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email');
$table->string('phone');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @returnvoid
*/
publicfunctiondown()
{
Schema::dropIfExists('students');
}
}
Step 5: Once you are setup with your migration table as above, then lets migrate this table into database with following command:
$ php artisan migrate
your table will be migrated successfully into database after the above command.
Step 6: Now, we will create a Eloquent Model with the following command to manage or perform the database table operations.
$ php artisan make:model Student
after successful creation of model in the following path: app/Student.php open the file and follow as below:
<?php
namespaceApp;
use Illuminate\Database\Eloquent\Model;
classStudentextendsModel
{
protected$table = 'students'; //type the table name