1656727380
No Laravel, você não precisa escrever código longo para exportar seus dados, já existe um pacote disponível para isso – Laravel Excel.
Permite exportar dados em vários formatos como – XLSX, CSV, XLS, HTML, etc.
Neste tutorial, mostro como você pode exportar dados do banco de dados MySQL no formato CSV e Excel usando o pacote Laravel Excel no Laravel 8.
Requerimento -
^7.2\|^8.0
^5.8
^1.21
^1.0
php_zip
habilitadaphp_xml
habilitadaphp_gd2
habilitadaphp_iconv
habilitadaphp_simplexml
habilitadaphp_xmlreader
habilitadaphp_zlib
habilitadaInstale o pacote usando o compositor –
composer require maatwebsite/excel
Se você estiver recebendo um erro ao executar o comando acima, execute o comando abaixo –
composer require psr/simple-cache:^1.0 maatwebsite/excel
Depois disso, execute novamente –
composer require maatwebsite/excel
config/app.php
arquivo.Maatwebsite\Excel\ExcelServiceProvider::class
em 'providers'
–'providers' => [
....
....
....
Maatwebsite\Excel\ExcelServiceProvider::class
];
'Excel' => Maatwebsite\Excel\Facades\Excel::class
em 'aliases'
–'aliases' => [
....
....
....
'Excel' => Maatwebsite\Excel\Facades\Excel::class
];
Execute o comando -
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config
Isso criará um novo excel.php
arquivo em config/
.
Abrir .env
arquivo.
Especifique o host, o nome do banco de dados, o nome de usuário e a senha.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=
Employees
usando a migração e adicione alguns registros.php artisan make:migration create_employees_table
database/migrations/
pasta da raiz do projeto.create_employees_table
e abra-o.up()
método.public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->string('username');
$table->string('name');
$table->string('email');
$table->smallInteger('age');
$table->timestamps();
});
}
php artisan migrate
Employees
modelo.php artisan make:model Employees
app/Models/Employees.php
arquivo.$fillable
propriedade.Código concluído
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employees extends Model
{
use HasFactory;
protected $fillable = [
'username','name','email','age'
];
}
Estou criando 2 classes de exportação apenas para fins de exemplo -
1. Classe de Exportação de Funcionários -
php artisan make:export EmployeesExport --model=Employees
app/Exports/EmployeesExport.php
arquivo.A classe tem 2 métodos –
NOTA – Remova os métodos headers() se você não quiser adicionar uma linha de cabeçalho.
Código concluído
<?php
namespace App\Exports;
use App\Models\Employees;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class EmployeesExport implements FromCollection, WithHeadings
{
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
## 1. Export all data
// return Employees::all();
## 2. Export specific columns
return Employees::select('id','username','name')->get();
}
public function headings(): array
{
return [
'#',
'Username',
'Name'
];
}
}
2. FuncionáriosPor Classe de Exportação de Idade –
php artisan make:export EmployeesByAgeExport --model=Employees
app/Exports/EmployeesByAgeExport.php
arquivo.__construct()
para permitir o envio de um parâmetro ao criar a instância da classe e usá-lo para recuperar dados.$result
Array passe $result
para collect()
retorno –return collect($result);
heading()
método.Código concluído
<?php
namespace App\Exports;
use App\Models\Employees;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class EmployeesByAgeExport implements FromCollection, WithHeadings
{
private $agegreaterthan;
public function __construct($age=0)
{
$this->agegreaterthan = $age;
}
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
## 3. Conditional export and customize result
$records = Employees::select('*')->where('age','>',$this->agegreaterthan)->get();
$result = array();
foreach($records as $record){
$result[] = array(
'id'=>$record->id,
'username' => $record->username,
'name' => $record->name,
'email' => $record->email,
'age' => $record->age,
'status' => 1 // Custom data
);
}
return collect($result);
}
public function headings(): array
{
return [
'#',
'Username',
'Name',
'Email',
'Age',
'Status'
];
}
}
routes/web.php
arquivo.Código concluído
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeesController;
Route::get('/', [EmployeesController::class, 'index'])->name('home');
Route::get('employees/exportcsv', [EmployeesController::class, 'exportCSV'])->name('employees.exportcsv');
Route::get('employees/exportexcel', [EmployeesController::class, 'exportExcel'])->name('employees.exportexcel');
Route::post('employees/exportbyagecsv', [EmployeesController::class, 'exportByAgeCSV'])->name('employees.exportbyagecsv');
EmployeesController
controlador.php artisan make:controller EmployeesController
app/Http/Controllers/EmployeesController.php
arquivo.EmployeesExport
_ EmployeesByAgeExportExcel
index
visualização.Excel::download()
.Leva 2 parâmetros -
$file_name = 'employees_'.date('Y_m_d_H_i_s').'.csv';
return Excel::download(new EmployeesExport, $file_name);
EmployeesByAgeExport($age)
instância.$file_name = 'employees_'.date('Y_m_d_H_i_s').'.csv';
return Excel::download(new EmployeesByAgeExport($age), $file_name);
Código concluído
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Exports\EmployeesExport;
use App\Exports\EmployeesByAgeExport;
use Excel;
class EmployeesController extends Controller
{
public function index(){
return view('index');
}
// CSV Export
public function exportCSV(){
$file_name = 'employees_'.date('Y_m_d_H_i_s').'.csv';
return Excel::download(new EmployeesExport, $file_name);
}
// Excel Export
public function exportExcel(){
$file_name = 'employees_'.date('Y_m_d_H_i_s').'.xlsx';
return Excel::download(new EmployeesExport, $file_name);
}
// Conditional Export (csv)
public function exportByAgeCSV(Request $request){
$age = $request->age;
$file_name = 'employees_'.date('Y_m_d_H_i_s').'.csv';
return Excel::download(new EmployeesByAgeExport($age), $file_name);
}
}
Criar index.blade.php
arquivo na resources/views/
pasta.
Crie 2 elementos âncora –
href
como {{ route('employees.exportcsv') }}
para exportação CSV.href
como {{ route('employees.exportexcel') }}
para exportação do Excel.Crie um <form method='post' action="{{ route('employees.exportbyagecsv') }}">
. Adicione um elemento de entrada para inserir a idade e um botão de envio.
Código concluído
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How to Export data to CSV & Excel format in Laravel 8</title>
<!-- CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" >
</head>
<body>
<div class="container mt-5">
<a class="btn btn-primary" href="{{ route('employees.exportcsv') }}">CSV Export</a>
<a class="btn btn-primary" href="{{ route('employees.exportexcel') }}">Excel Export</a><br><br>
<form method='post' action="{{ route('employees.exportbyagecsv') }}">
@csrf
<div class="mb-3">
<label for="age" class="form-label">Age</label>
<input type="number" class="form-control" id="age" name="age" value="0">
</div>
<button type="submit" class="btn btn-success">Export</button>
</form>
</div>
</body>
</html>
Use o construtor na classe Export para manipular os parâmetros passados e use-o para buscar dados.
Neste tutorial, mencionei apenas 2 formatos de exportação – CSV e Excel, mas há mais formatos disponíveis.
Fonte: https://makitweb.com
1656727380
No Laravel, você não precisa escrever código longo para exportar seus dados, já existe um pacote disponível para isso – Laravel Excel.
Permite exportar dados em vários formatos como – XLSX, CSV, XLS, HTML, etc.
Neste tutorial, mostro como você pode exportar dados do banco de dados MySQL no formato CSV e Excel usando o pacote Laravel Excel no Laravel 8.
Requerimento -
^7.2\|^8.0
^5.8
^1.21
^1.0
php_zip
habilitadaphp_xml
habilitadaphp_gd2
habilitadaphp_iconv
habilitadaphp_simplexml
habilitadaphp_xmlreader
habilitadaphp_zlib
habilitadaInstale o pacote usando o compositor –
composer require maatwebsite/excel
Se você estiver recebendo um erro ao executar o comando acima, execute o comando abaixo –
composer require psr/simple-cache:^1.0 maatwebsite/excel
Depois disso, execute novamente –
composer require maatwebsite/excel
config/app.php
arquivo.Maatwebsite\Excel\ExcelServiceProvider::class
em 'providers'
–'providers' => [
....
....
....
Maatwebsite\Excel\ExcelServiceProvider::class
];
'Excel' => Maatwebsite\Excel\Facades\Excel::class
em 'aliases'
–'aliases' => [
....
....
....
'Excel' => Maatwebsite\Excel\Facades\Excel::class
];
Execute o comando -
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config
Isso criará um novo excel.php
arquivo em config/
.
Abrir .env
arquivo.
Especifique o host, o nome do banco de dados, o nome de usuário e a senha.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=
Employees
usando a migração e adicione alguns registros.php artisan make:migration create_employees_table
database/migrations/
pasta da raiz do projeto.create_employees_table
e abra-o.up()
método.public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->string('username');
$table->string('name');
$table->string('email');
$table->smallInteger('age');
$table->timestamps();
});
}
php artisan migrate
Employees
modelo.php artisan make:model Employees
app/Models/Employees.php
arquivo.$fillable
propriedade.Código concluído
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employees extends Model
{
use HasFactory;
protected $fillable = [
'username','name','email','age'
];
}
Estou criando 2 classes de exportação apenas para fins de exemplo -
1. Classe de Exportação de Funcionários -
php artisan make:export EmployeesExport --model=Employees
app/Exports/EmployeesExport.php
arquivo.A classe tem 2 métodos –
NOTA – Remova os métodos headers() se você não quiser adicionar uma linha de cabeçalho.
Código concluído
<?php
namespace App\Exports;
use App\Models\Employees;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class EmployeesExport implements FromCollection, WithHeadings
{
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
## 1. Export all data
// return Employees::all();
## 2. Export specific columns
return Employees::select('id','username','name')->get();
}
public function headings(): array
{
return [
'#',
'Username',
'Name'
];
}
}
2. FuncionáriosPor Classe de Exportação de Idade –
php artisan make:export EmployeesByAgeExport --model=Employees
app/Exports/EmployeesByAgeExport.php
arquivo.__construct()
para permitir o envio de um parâmetro ao criar a instância da classe e usá-lo para recuperar dados.$result
Array passe $result
para collect()
retorno –return collect($result);
heading()
método.Código concluído
<?php
namespace App\Exports;
use App\Models\Employees;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class EmployeesByAgeExport implements FromCollection, WithHeadings
{
private $agegreaterthan;
public function __construct($age=0)
{
$this->agegreaterthan = $age;
}
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
## 3. Conditional export and customize result
$records = Employees::select('*')->where('age','>',$this->agegreaterthan)->get();
$result = array();
foreach($records as $record){
$result[] = array(
'id'=>$record->id,
'username' => $record->username,
'name' => $record->name,
'email' => $record->email,
'age' => $record->age,
'status' => 1 // Custom data
);
}
return collect($result);
}
public function headings(): array
{
return [
'#',
'Username',
'Name',
'Email',
'Age',
'Status'
];
}
}
routes/web.php
arquivo.Código concluído
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeesController;
Route::get('/', [EmployeesController::class, 'index'])->name('home');
Route::get('employees/exportcsv', [EmployeesController::class, 'exportCSV'])->name('employees.exportcsv');
Route::get('employees/exportexcel', [EmployeesController::class, 'exportExcel'])->name('employees.exportexcel');
Route::post('employees/exportbyagecsv', [EmployeesController::class, 'exportByAgeCSV'])->name('employees.exportbyagecsv');
EmployeesController
controlador.php artisan make:controller EmployeesController
app/Http/Controllers/EmployeesController.php
arquivo.EmployeesExport
_ EmployeesByAgeExportExcel
index
visualização.Excel::download()
.Leva 2 parâmetros -
$file_name = 'employees_'.date('Y_m_d_H_i_s').'.csv';
return Excel::download(new EmployeesExport, $file_name);
EmployeesByAgeExport($age)
instância.$file_name = 'employees_'.date('Y_m_d_H_i_s').'.csv';
return Excel::download(new EmployeesByAgeExport($age), $file_name);
Código concluído
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Exports\EmployeesExport;
use App\Exports\EmployeesByAgeExport;
use Excel;
class EmployeesController extends Controller
{
public function index(){
return view('index');
}
// CSV Export
public function exportCSV(){
$file_name = 'employees_'.date('Y_m_d_H_i_s').'.csv';
return Excel::download(new EmployeesExport, $file_name);
}
// Excel Export
public function exportExcel(){
$file_name = 'employees_'.date('Y_m_d_H_i_s').'.xlsx';
return Excel::download(new EmployeesExport, $file_name);
}
// Conditional Export (csv)
public function exportByAgeCSV(Request $request){
$age = $request->age;
$file_name = 'employees_'.date('Y_m_d_H_i_s').'.csv';
return Excel::download(new EmployeesByAgeExport($age), $file_name);
}
}
Criar index.blade.php
arquivo na resources/views/
pasta.
Crie 2 elementos âncora –
href
como {{ route('employees.exportcsv') }}
para exportação CSV.href
como {{ route('employees.exportexcel') }}
para exportação do Excel.Crie um <form method='post' action="{{ route('employees.exportbyagecsv') }}">
. Adicione um elemento de entrada para inserir a idade e um botão de envio.
Código concluído
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How to Export data to CSV & Excel format in Laravel 8</title>
<!-- CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" >
</head>
<body>
<div class="container mt-5">
<a class="btn btn-primary" href="{{ route('employees.exportcsv') }}">CSV Export</a>
<a class="btn btn-primary" href="{{ route('employees.exportexcel') }}">Excel Export</a><br><br>
<form method='post' action="{{ route('employees.exportbyagecsv') }}">
@csrf
<div class="mb-3">
<label for="age" class="form-label">Age</label>
<input type="number" class="form-control" id="age" name="age" value="0">
</div>
<button type="submit" class="btn btn-success">Export</button>
</form>
</div>
</body>
</html>
Use o construtor na classe Export para manipular os parâmetros passados e use-o para buscar dados.
Neste tutorial, mencionei apenas 2 formatos de exportação – CSV e Excel, mas há mais formatos disponíveis.
Fonte: https://makitweb.com
1656702180
A importação de dados em massa é um recurso útil para adicionar registros armazenados em um arquivo ao banco de dados. Os dados podem ser armazenados em formato – CSV, Excel, XML, ODS, etc.
Neste tutorial, mostro como você pode importar dados CSV e Excel para o banco de dados MySQL usando o pacote Laravel Excel no projeto Laravel 8.
Requerimento -
^7.2\|^8.0
^5.8
^1.21
^1.0
php_zip
habilitadaphp_xml
habilitadaphp_gd2
habilitadaphp_iconv
habilitadaphp_simplexml
habilitadaphp_xmlreader
habilitadaphp_zlib
habilitadaInstale o pacote usando o compositor –
composer require maatwebsite/excel
Se você estiver recebendo um erro ao executar o comando acima, execute o comando abaixo –
composer require psr/simple-cache:^1.0 maatwebsite/excel
Depois disso, execute novamente –
composer require maatwebsite/excel
config/app.php
arquivo.Maatwebsite\Excel\ExcelServiceProvider::class
em 'providers'
–'providers' => [
....
....
....
Maatwebsite\Excel\ExcelServiceProvider::class
];
'Excel' => Maatwebsite\Excel\Facades\Excel::class
em 'aliases'
–'aliases' => [
....
....
....
'Excel' => Maatwebsite\Excel\Facades\Excel::class
];
Execute o comando -
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config
Isso criará um novo excel.php
arquivo em config/
.
Abrir .env
arquivo.
Especifique o host, o nome do banco de dados, o nome de usuário e a senha.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=
Employees
usando a migração e adicione alguns registros.php artisan make:migration create_employees_table
database/migrations/
pasta da raiz do projeto.create_employees_table
e abra-o.up()
método.public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->string('username');
$table->string('name');
$table->string('email');
$table->smallInteger('age');
$table->timestamps();
});
}
php artisan migrate
Employees
modelo.php artisan make:model Employees
app/Models/Employees.php
arquivo.$fillable
propriedade.Código concluído
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employees extends Model
{
use HasFactory;
protected $fillable = [
'username','name','email','age'
];
}
Estou criando 2 classes de importação apenas para fins de exemplo -
1. Classe de importação de funcionários -
php artisan make:import EmployeesImport --model=Employees
app/Imports/EmployeesImport.php
arquivo.$row
Array e insere um registro se o ID do email não existir na employees
tabela, caso contrário, retorna null.NOTA – Esta classe de importação começa a ler os registros da 1ª linha. Expliquei como pular a primeira linha que contém o título na próxima classe de importação.
Arquivo CSV sem linha de cabeçalho –
usuário1 | Usuário1 u1 | user1@makitweb.com | 28 |
usuário2 | Usuário2 u2 | user2@makitweb.com | 24 |
Código concluído
<?php
namespace App\Imports;
use App\Models\Employees;
use Maatwebsite\Excel\Concerns\ToModel;
class EmployeesImport implements ToModel {
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row) {
// Check email already exists
$count = Employees::where('email',$row[2])->count();
if($count > 0){
return null;
}
return new Employees([
'username' => $row[0],
'name' => $row[1],
'email' => $row[2],
'age' => $row[3],
]);
}
}
2. Empregados2 Classe de Importação -
php artisan make:import Employees2Import --model=Employees
app/Imports/Employees2Import.php
arquivo.$rows
os dados do Array. Se validado com sucesso, insira o registro se o ID do email não existir na employees
tabela, caso contrário, retorne o erro.OBSERVAÇÃO – Se
WithHeadingRow
for implementado,$rows
Arrays conterá cabeçalho de linha como nomes de chave em vez de índice.
Arquivo CSV com linha de título –
Nome de usuário | Nome | Era | |
---|---|---|---|
yssyogesh | Yogesh singh | yogesh@makitweb.com | 28 |
bsonarika | Sonarika Bhadoria | bsonarika@makitweb.com | 28 |
vishal | Vishal Sahu | vishal@makitweb.com | trigésimo primeiro |
Código concluído
<?php
namespace App\Imports;
use App\Models\Employees;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Facades\Validator;
class Employees2Import implements ToCollection ,WithHeadingRow
{
public function collection(Collection $rows){
// Validate
Validator::make($rows->toArray(), [
'*.username' => 'required|string',
'*.name' => 'required|string',
'*.email' => 'required|email',
'*.age' => 'required|integer',
],[
'*.username.required'=> "The username field is required.",
'*.username.string'=> "The username must be string.",
'*.name.required'=> "The name field is required.",
'*.name.string'=> "The name must be string.",
'*.email.required'=> "The email field is required.",
'*.email.email'=> "The email must be a valid email address.",
'*.age.integer'=> "The age must be an integer."
])->validate();
foreach ($rows as $row) {
// Check email already exists
$count = Employees::where('email',$row['email'])->count();
if($count > 0){
continue;
}
Employees::create([
'username' => $row['username'],
'name' => $row['name'],
'email' => $row['email'],
'age' => $row['age'],
]);
}
}
// Specify header row index position to skip
public function headingRow(): int {
return 1;
}
}
routes/web.php
arquivo.Código concluído
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeesController;
Route::get('/', [EmployeesController::class, 'index'])->name('home');
Route::post('employees/importdata/', [EmployeesController::class, 'importData'])->name('employees.importdata');
Route::post('employees/validateandimportdata/', [EmployeesController::class, 'validateAndImportdata'])->name('employees.validateandimportdata');
EmployeesController
controlador.php artisan make:controller EmployeesController
app/Http/Controllers/EmployeesController.php
arquivo.EmployeesImport
_ Employees2ImportExcel
index
visualização.Excel::import()
.Passe 2 parâmetros –
EmployeesImport
Instância de classe.Excel::import()
.Passe 2 parâmetros –
Employees2Import
Instância de classe.public/employees.xlsx
pasta).Código concluído
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Imports\EmployeesImport;
use App\Imports\Employees2Import;
use Excel;
class EmployeesController extends Controller
{
public function index(){
return view('index');
}
// Import data
public function importdata(Request $request){
Excel::import(new EmployeesImport, $request->file('file')->store('temp'));
return back()->with('success', 'Import successfully!');
}
// Validate and Import data
public function validateAndImportdata(Request $request){
Excel::import(new Employees2Import, "employees.xlsx");
return back()->with('success', 'Import successfully!');
}
}
Criar index.blade.php
arquivo na resources/views/
pasta.
Criar 2 <form>
-
<form >
ação definida para {{ route('employees.importdata') }}
. Crie um elemento de arquivo e um botão de envio.<form>
ação defina para {{ route('employees.validateandimportdata') }}
. Crie um botão de envio.Faça um loop $errors->all()
para exibir erros.
Código concluído
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How to Import data into MySQL database in Laravel 8</title>
<!-- CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" >
</head>
<body>
<div class="container mt-5">
<!-- Success message -->
@if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
</div>
@endif
<form method='post' action="{{ route('employees.importdata') }}" enctype="multipart/form-data">
@csrf
<div class="mb-3">
<label for="file" class="form-label">File</label>
<input type="file" class="form-control" id="file" name="file" value="">
</div>
<button type="submit" class="btn btn-success">Import</button>
</form>
<!-- Import data with validation -->
<h2 class='mt-5'>Validate and import data</h2>
{{-- Display errors --}}
@if (count($errors) > 0)
<div class="row">
<div class="col-md-12 ">
<div class="alert alert-danger">
<ul>
@foreach($errors->all() as $error)
<li>{{ $error }} </li>
@endforeach
</ul>
</div>
</div>
</div>
@endif
<form method='post' action="{{ route('employees.validateandimportdata') }}" >
@csrf
<button type="submit" class="btn btn-success">Import</button>
</form>
</div>
</body>
</html>
Certifique-se de validar o registro antes de inserir ou atualizar registros na classe Import. Especifique WithHeadingRow
na classe Import apenas se o arquivo de importação tiver uma linha de cabeçalho.
Fonte: https://makitweb.com
1595905879
HTML to Markdown
MySQL is the all-time number one open source database in the world, and a staple in RDBMS space. DigitalOcean is quickly building its reputation as the developers cloud by providing an affordable, flexible and easy to use cloud platform for developers to work with. MySQL on DigitalOcean is a natural fit, but what’s the best way to deploy your cloud database? In this post, we are going to compare the top two providers, DigitalOcean Managed Databases for MySQL vs. ScaleGrid MySQL hosting on DigitalOcean.
At a glance – TLDR
ScaleGrid Blog - At a glance overview - 1st pointCompare Throughput
ScaleGrid averages almost 40% higher throughput over DigitalOcean for MySQL, with up to 46% higher throughput in write-intensive workloads. Read now
ScaleGrid Blog - At a glance overview - 2nd pointCompare Latency
On average, ScaleGrid achieves almost 30% lower latency over DigitalOcean for the same deployment configurations. Read now
ScaleGrid Blog - At a glance overview - 3rd pointCompare Pricing
ScaleGrid provides 30% more storage on average vs. DigitalOcean for MySQL at the same affordable price. Read now
MySQL DigitalOcean Performance Benchmark
In this benchmark, we compare equivalent plan sizes between ScaleGrid MySQL on DigitalOcean and DigitalOcean Managed Databases for MySQL. We are going to use a common, popular plan size using the below configurations for this performance benchmark:
Comparison Overview
ScaleGridDigitalOceanInstance TypeMedium: 4 vCPUsMedium: 4 vCPUsMySQL Version8.0.208.0.20RAM8GB8GBSSD140GB115GBDeployment TypeStandaloneStandaloneRegionSF03SF03SupportIncludedBusiness-level support included with account sizes over $500/monthMonthly Price$120$120
As you can see above, ScaleGrid and DigitalOcean offer the same plan configurations across this plan size, apart from SSD where ScaleGrid provides over 20% more storage for the same price.
To ensure the most accurate results in our performance tests, we run the benchmark four times for each comparison to find the average performance across throughput and latency over read-intensive workloads, balanced workloads, and write-intensive workloads.
Throughput
In this benchmark, we measure MySQL throughput in terms of queries per second (QPS) to measure our query efficiency. To quickly summarize the results, we display read-intensive, write-intensive and balanced workload averages below for 150 threads for ScaleGrid vs. DigitalOcean MySQL:
ScaleGrid MySQL vs DigitalOcean Managed Databases - Throughput Performance Graph
For the common 150 thread comparison, ScaleGrid averages almost 40% higher throughput over DigitalOcean for MySQL, with up to 46% higher throughput in write-intensive workloads.
#cloud #database #developer #digital ocean #mysql #performance #scalegrid #95th percentile latency #balanced workloads #developers cloud #digitalocean droplet #digitalocean managed databases #digitalocean performance #digitalocean pricing #higher throughput #latency benchmark #lower latency #mysql benchmark setup #mysql client threads #mysql configuration #mysql digitalocean #mysql latency #mysql on digitalocean #mysql throughput #performance benchmark #queries per second #read-intensive #scalegrid mysql #scalegrid vs. digitalocean #throughput benchmark #write-intensive
1622622360
In this tutorial, let’s discuss what data validation is and how it can be implemented in MS-Excel. Let’s start!!!
Data Validation is one of the features in MS-Excel which helps in maintaining the consistency of the data in the spreadsheet. It controls the type of data that can enter in the data validated cells.
Now, let’s have a look at how data validation works and how to implement it in the worksheet:
To apply data validation for the cells, then follow the steps.
1: Choose to which all cells the validation of data should work.
2: Click on the DATA tab.
3: Go to the Data Validation option.
4: Choose the drop down option in it and click on the Data Validation.
Once you click on the data validation menu from the ribbon, a box appears with the list of data validation criteria, Input message and error message.
Let’s first understand, what is an input message and error message?
Once, the user clicks the cell, the input message appears in a small box near the cell.
If the user violates the condition of that particular cell, then the error message pops up in a box in the spreadsheet.
The advantage of both the messages is that the input and as well as the error message guide the user about how to fill the cells. Both the messages are customizable also.
Let us have a look at how to set it up and how it works with a sample
#ms excel tutorials #circle invalid data in excel #clear validation circles in excel #custom data validation in excel #data validation in excel #limitation in data validation in excel #setting up error message in excel #setting up input message in excel #troubleshooting formulas in excel #validate data in excel
1622608201
In this post i will show you Laravel 8 Import Export CSV/EXCEL File Example. We will simple create import data to xls, csv file and also we will import data to database using csv file in laravel 8 application.
Using this example we can easily import-export and download the csv & excel file from the database using the maatwebsite/excel composer package. maatwebsite/excel provide easy way to import and export csv file in laravel 8 using database model.
#laravel 8 import export csv/excel file example #laravel 8 #import #export #csv/excel #import and export csv file in laravel 8