Code to insert bulk records of data into database using Laravel/Lumen query builder
Let's say below is your table structure. The table name is the person with the below columns: id int(11), firstName varchar(100), lastName varchar(100), age int(3), address varchar(200), created timestamp If you want to write a query to insert 50 records at a time instead of inserting 50 times in a loop then you can use the query builder style to write like below: <?php $data = array(); foreach ($records as $row) { // Create an array of data where one array is a row so that // multiple rows can be inserted at a time $data[] = [ 'firstName' => $row['firstName'], 'lastName' => $row['lastName'], 'age' => $row['age'], 'address' => $row['address'], ]; } DB::table('person')->insert($data); Let me know if you have any questions :) Thanks!
Run artisan to migrate and seed into the database.
php artisan migrate
php artisan db:seed
Step 4: User interface setup in Laravel
User model file
Now open the user.php model file from inside the app folder and add the below code to it.
<?phpnamespaceApp\Models;useIlluminate\Contracts\Auth\MustVerifyEmail;useIlluminate\Foundation\Auth\Useras Authenticatable;useIlluminate\Notifications\Notifiable;useTymon\JWTAuth\Contracts\JWTSubject;classUserextendsAuthenticatableimplementsJWTSubject{useNotifiable;/**
* The attributes that are mass assignable.
*
* @vararray */protected$fillable=['name','email','password',];/**
* The attributes that should be hidden for arrays.
*
* @vararray */protected$hidden=['password','remember_token',];publicfunctiongetJWTIdentifier(){return$this->getKey();}publicfunctiongetJWTCustomClaims(){return[];}/**
* The attributes that should be cast to native types.
*
* @vararray */protected$casts=['email_verified_at'=>'datetime',];}
User Controller file
Create the ../app/Http/Controllers/UserController.php file and add the below code to it.
Register, login, and get authenticated user functions are defined in this controller.
To create the routes open routes file located here ../routes/web.php and add below routes in it.
<?phpuseIlluminate\Support\Facades\Route;/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/Route::get('/',function(){returnview('welcome');});Auth::routes();Route::get('/home','HomeController@index')->name('home');
After creating web routes, now we can open the project in the browser to check if that is working.
Now open the API routes file located here ../routes/api.php and add the below routes in it.
<?phpuseIlluminate\Http\Request;useIlluminate\Support\Facades\Route;useApp\Http\Controllers\UserController;/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/Route::middleware('auth:api')->get('/user',function(Request$request){return$request->user();});Route::post('register',[UserController::class,'register']);Route::post('login',[UserController::class,'login']);Route::get('profile',[UserController::class,'getAuthenticatedUser']);
After creating API routes, now we can check the created APIs using postman.
Step 6: JWT key / secret
Run PHP artisan to use JWT for authentication and authorization.
php artisan key:generate
php artisan jwt:secret(php artisan serve&)// To run on background
Check the register and login API’s on the postman. We already have defined functionality in the UserController.php file for these API’s.
Register API test
Login API test
Step 7: Install Dependencies
If you do not have the laravel UI installed for bootstrap the run below command.
composer require laravel/ui
php artisan ui vue
Make sure you have installed node, npm, and vue. If you haven’t installed it then follow the below command.
npm install && npm run dev
php artisan ui vue --auth
npm install
Step 7: Set up Vue components
In step 1, we already have set up the Vue application.
Now open package.json file from the vueapp directory. ../vueapp/package.json and add the dependencies. Add axios and bootstrap dependencies. After adding it will look like this.
Run the below command in the terminal. This command will install the packages that we have just added above.
npm i
Now, Open ../vueapp/config/index.js file and update the below code in it.
'use strict'// Template version: 1.3.1// see http://vuejs-templates.github.io/webpack for documentation.const path =require('path')module.exports={dev:{// PathsassetsSubDirectory:'static',assetsPublicPath:'/',proxyTable:{},// Various Dev Server settingshost:'localhost',// can be overwritten by process.env.HOSTport:8080,// can be overwritten by process.env.PORT, if port is in use, a free one will be determinedautoOpenBrowser:false,errorOverlay:true,notifyOnErrors:true,poll:false,// https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-// Use Eslint Loader?// If true, your code will be linted during bundling and// linting errors and warnings will be shown in the console.useEslint:true,// If true, eslint errors and warnings will also be shown in the error overlay// in the browser.showEslintErrorsInOverlay:false,/**
* Source Maps
*/// https://webpack.js.org/configuration/devtool/#developmentdevtool:'cheap-module-eval-source-map',// If you have problems debugging vue-files in devtools,// set this to false - it *may* help// https://vue-loader.vuejs.org/en/options.html#cachebustingcacheBusting:true,cssSourceMap:true},build:{// Template for index.htmlindex: path.resolve(__dirname,'../dist/index.html'),// PathsassetsRoot: path.resolve(__dirname,'../dist'),assetsSubDirectory:'static',assetsPublicPath:'/',/**
* Source Maps
*/productionSourceMap:true,// https://webpack.js.org/configuration/devtool/#productiondevtool:'#source-map',// Gzip off by default as many popular static hosts such as// Surge or Netlify already gzip all static assets for you.// Before setting to `true`, make sure to:// npm install --save-dev compression-webpack-pluginproductionGzip:false,productionGzipExtensions:['js','css'],// Run the build command with an extra argument to// View the bundle analyzer report after build finishes:// `npm run build --report`// Set to `true` or `false` to always turn it on or offbundleAnalyzerReport: process.env.npm_config_report}}
Open ../client/src/main.js file and update code same as below.
// The Vue build version to load with the `import` command// (runtime-only or standalone) has been set in webpack.base.conf with an alias.importVuefrom'vue'importAppfrom'./App'importrouterfrom'./router'require('../node_modules/bootstrap/dist/css/bootstrap.css')Vue.config.productionTip=false/* eslint-disable no-new */newVue({el:'#app', router,components:{App},template:'<App/>'})
Open ../client/src/App.vue file and update code same as below.
open file ../vueapp/src/router/index.js and add thebelow code in it.
importVuefrom'vue'importRouterfrom'vue-router'// import HelloWorld from '@/components/HelloWorld'importHomefrom'../components/Home'importLoginfrom'../components/Login'importRegisterfrom'../components/Register'importProfilefrom'../components/Profile'Vue.use(Router)exportdefaultnewRouter({routes:[{path:'/',name:'Home',component:Home},{path:'/login',name:'Login',component:Login},{path:'/register',name:'Register',component:Register},{path:'/profile',name:'Profile',component:Profile}]})
Here we have added the routes for vue.
Now create the component of vue inside this folder ../vueapp/src/components and create a new file for that and will add the code in it.
Now open the tests/TestCase.php file from inside the app folder and update the below code to it.
<?php
namespace Tests;
use Faker\Factory;
abstract class TestCase extends \Illuminate\Foundation\Testing\TestCase
{
use CreatesApplication;
protected $faker;
/**
* To generate test data using faker and seeder
*
* @return void
*/
public function setUp(): void
{
parent::setUp();
$this->artisan('migrate');
$this->artisan('db:seed');
$this->faker = Factory::create();
}
}
Now create a file tests/app/Http/Controllers/UserCase.php file from inside the app folder and add the below code to it.
<?php
/**
* Unit test for the end points used in UserController
*
* @category Test Case File
* @license Not licensed for external use
*/
class UserTest extends \Tests\TestCase
{
/**
* Create user
*/
public function testRegister()
{
$faker = $this->faker;
$parameters = [
'name' => $faker->name,
'email' => !empty($email) ? $email
: preg_replace(
'/@example\..*/',
'@mailinator.com',
$faker->unique()->safeEmail
),
'password' => $faker->password,
];
$result = $this->post("api/register", $parameters);
$this->assertJson($result->json(),'{"name":[""],"email":[""],"password":[""]}');
}
}
On terminal run the below command to execute the PHPUnit test.
./vendor/bin/phpunit tests
Result :
So now we are done with the PHPUnit test for one of the laravel API endpoint.
Test Your Vue Components Using the Jest Testing Framework
Jest is a popular JavaScript testing framework. Lets setup the tester for Vue components.
Setup and Installing Dependencies
If you don’t have the Vue CLI installed on your machine already, start by running either:
$ npm install -g @vue/cli
Run the following command to add our testing dependencies (@vue/cli-plugin-unit-jest and @vue/test-utils):
Then go ahead and run $ npm run serve from the root directory of your project.
Now you head over to localhost:8000 in your browser and see the working app.
Testing the App with Jest
Created a file called JestTest.spec.js. By default, jest will catch any test files (searching recursively through folders) in your project that are named *.spec.js or *.test.js.
At the top of JestTest.spec.js we’re going to import the following from @vue/test-utils as well as our JestTest component itself:
Here the test covered the data and methods exported on the Vue component.