get data after save excel file with `maatwebsite/excel` - php

Project in Laravel (9), and PHP (8.1).
I want to import an excel file and use maatwebsite/excel (3.1) package.
I can import a file, and save the file into the model, like this:
import class:
class BankTransfersHistoryImport implements ToModel, WithHeadingRow, WithValidation
{
use Importable;
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new BankTransfersHistory([
'loanId' => $row['loanId'],
'actionDate' => transformDate($row['actionDate']),
'worth' => $row['worth'],
.
.
]);
}
public function headingRow(): int
{
return 2;
}
public function rules(): array
{
return [
'*.loanId' => ['required', 'numeric'],
... some roles ...
];
}
}
controller:
$import = new BankTransfersHistoryImport;
try {
// date validation
$collection = $import->toCollection($file);
... some validation about the date ...
$import->import($file);
... check and update rows ...
return [
"message" => some message,
"data" => [
some data
],
];
} catch (\Maatwebsite\Excel\Validators\ValidationException$e) {
$failures = $e->failures();
foreach ($failures as $failure) {
$failure->row(); // row that went wrong
$failure->attribute(); // either heading key (if using heading row concern) or column index
$failure->errors(); // Actual error messages from Laravel validator
$failure->values(); // The values of the row that has failed.
}
return $failures;
}
My question is:
If I can get the response of the file after saving the data, and that will give me the data with the id of the row that was saved.
In some cases, I will have to update a row. That's why I would like to get the ID.
Now in the check and update rows section, I update by loanId + actionDate. I want it to be done by ID.
something like this:
code:
$data = $import->import($file);
data will be like:
[
{
"id": 1,
"loanId": 21001,
"actionDate": "2020-01-02T00:00:00.000000Z",
"worth": 2997.09,
"offerId": 1,
},
{
"id": 2,
"loanId": 21002,
"actionDate": "2020-01-02T00:00:00.000000Z",
"worth": 3000,
"offerId": 10,
},
]

You can create a function on import class which will return the imported data, adding a sample for your reference.
UsersImport.php
<?php
namespace App\Imports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
class UsersImport implements ToModel
{
private $rows;
public function __construct() {
$this->rows = collect();
}
/**
* #param array $row
*
* #return User|null
*/
public function model(array $row)
{
$user = new User([
'name' => $row[0],
'email' => $row[1],
'password' => bcrypt(12345678),
]);
$this->rows->push($user);
return $user;
}
/**
* Returns Imported Data
*
* #return \Illuminate\Support\Collection
*/
public function getImportedData(): \Illuminate\Support\Collection
{
return $this->rows;
}
}
Your Import Function in Controller
public function import(UsersImport $usersImport)
{
Excel::import($usersImport, public_path('users.xlsx'));
$usersImport->getImportedData();
}

Related

Laravel excel, update rows after save in DB

Project in Laravel (9), and PHP (8.1).
I want to import an excel file and use maatwebsite/excel (3.1) package.
I can import a file, and save the file into the model, like this:
import class:
class BankTransfersHistoryImport implements ToModel, WithHeadingRow, WithValidation, WithBatchInserts
{
use Importable;
private $rows;
public function __construct()
{
$this->rows = collect();
}
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
$bankTransferHistory = new BankTransfersHistory([
'loanId' => $row['loanId'],
'actionDate' => transformDate($row['actionDate']),
'worth' => $row['worth'],
.
.
]);
$this->rows->push($bankTransferHistory);
return $bankTransferHistory;
}
/**
* Returns Imported Data
*
* #return \Illuminate\Support\Collection
*/
public function getImportedData(): \Illuminate\Support\Collection
{
return $this->rows;
}
public function headingRow(): int
{
return 2;
}
public function rules(): array
{
return [
'*.loanId' => ['required', 'numeric'],
... some roles ...
];
}
}
controller:
public function store(Request $request)
{
$request->validate([
'file' => 'required|mimes:xls,xlsx',
]);
$file = $request->file('file');
$import = new BankTransfersHistoryImport;
try {
// date validation
$collection = $import->toCollection($file);
... some validation about the date ...
$import->import($file);
$getImportedData = import->getImportedData();
... check and update rows ...
return [
"message" => some message,
"data" => [
some data
],
];
} catch (\Maatwebsite\Excel\Validators\ValidationException$e) {
$failures = $e->failures();
foreach ($failures as $failure) {
$failure->row(); // row that went wrong
$failure->attribute(); // either heading key (if using heading row concern) or column index
$failure->errors(); // Actual error messages from Laravel validator
$failure->values(); // The values of the row that has failed.
}
return $failures;
}
My question is:
If I can get the response of the file after saving the data, that will give me the data with the id of the row that was saved.
In some cases, I will have to update a row. That's why I would like to get the ID.
Now, in the check and update rows section, I update row by loanId + actionDate. I want it to be done by only ID.
something like this:
code:
$getImportedData = import->getImportedData();
data will be like:
[
{
"id": 1,
"loanId": 21001,
"actionDate": "2020-01-02T00:00:00.000000Z",
"worth": 2997.09,
"offerId": 1,
},
{
"id": 2,
"loanId": 21002,
"actionDate": "2020-01-02T00:00:00.000000Z",
"worth": 3000,
"offerId": 10,
},
]
The solution to my problem.
To save the information and get the ID of each saved row, I did a few things.
I changed my import class.
First I changed the create from ToModel to ToCollection
I deleted WithBatchInserts because this method does not work with ToCollection.
Next, I called the getImportedData function.
That's how I got all the rows I create in the DB with their ID.
This solved the problem for me to get the information saved with the ID of each line, and perform validation + update if necessary.
The code is below.
A small note:
I changed the word rows to data in the `getImportedData' function.
I save all the files in the system.
import class:
class BankTransfersHistoryImport implements ToCollection, WithHeadingRow, WithValidation
{
use Importable;
private $data;
public function __construct()
{
$this->data = collect();
}
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function collection(Collection $rows)
{
foreach ($rows as $row) {
$bankTransferHistory = BankTransfersHistory::create([
'loanId' => $row['loanId'],
'actionDate' => transformDate($row['actionDate']),
'worth' => $row['worth'],
.
.
]);
$this->data->push($bankTransferHistory);
}
}
/**
* Returns Imported Data
*
* #return \Illuminate\Support\Collection
*/
public function getImportedData(): \Illuminate\Support\Collection
{
return $this->data;
}
public function headingRow(): int
{
return 2;
}
public function rules(): array
{
return [
'*.loanId' => ['required', 'numeric'],
... some roles ...
];
}
}
store controller:
public function store(Request $request)
{
$request->validate([
'file' => 'required|mimes:xls,xlsx',
]);
$file = $request->file('file');
$import = new BankTransfersHistoryImport;
try {
// date validation
$collection = $import->toCollection($file);
... some validation about the date ...
// save the file in the system
$fileName = time() . '-' . $file->getClientOriginalName();
$file->storeAs('import bank transfers history', $fileName);
$import->import($file);
$importedData = $import->getImportedData(); // data after save in DB
... check and update rows ...
return [
"message" => some message,
"data" => [
some data
],
];
} catch (\Maatwebsite\Excel\Validators\ValidationException$e) {
$failures = $e->failures();
foreach ($failures as $failure) {
$failure->row(); // row that went wrong
$failure->attribute(); // either heading key (if using heading row concern) or column index
$failure->errors(); // Actual error messages from Laravel validator
$failure->values(); // The values of the row that has failed.
}
return $failures;
}
}

How to create a new column when exporting a table. Laravel maatwebsite / excel

Please tell me, how create a new column when exporting(to exel) table. There is a table in DB of this kind:
I installed package for export maatwebsite / excel. There is also a my file of model:
class ScheduledInspectionModel extends Model
{
protected $table = 'scheduled_inspection'; // table name
protected $fillable = ['name_smp', 'name_control', "verification_start", "verification_end", 'verification_duration'];
public $timestamps = false;
}
Controller:
class OrganizationsExportController extends Controller
{
public function export()
{
return (new OrganizationsExport)->download('organizations_export.xls');
}
}
And file with export description:
class OrganizationsExport implements FromCollection, ShouldAutoSize, WithHeadings, WithEvents
{
use Exportable;
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return ScheduledInspectionModel::all();
}
public function headings(): array
{
return [
'id',
'Name SMP',
'Name Control',
'Verification Start',
'Verification End',
'Verification Duration'
];
}
public function registerEvents(): array
{
return [
AfterSheet::class => function (AfterSheet $event) {
$event->sheet->getStyle('A1:F1')->applyFromArray([
'font' => [
'bold' => true
]
]);
}
];
}
}
The exported table looks like this:
The export works :) But I want to create in place of the 'id' column (I can exclude it using map ()), 'Number' column and enter the line numbering accordingly. Please tell me how to do this?
I would use the map() function on the export, here you can tweak the source of each column. I assumed column names in your db, due to not knowing the structure. Add one to the count each time it is transformed and you should be golden, which is done with the ++ operator.
private $count = 0;
public function map(ScheduledInspectionModel $inspection): array
{
return [
++$this->count,
$inspection->name_smp,
$inspection->name_control,
$inspection->verification_start->format('Y-m-d') . ' - ' .$inspection->verification_end->format('Y-m-d'),
$inspection->duration,
];
}
To call format on dates, you have to set the dates array on your model.
class ScheduledInspectionModel {
protected $dates = [
'verification_start',
'verification_end',
];
}

how to skip the row about importing excel laravel with the Maatwebsite/Laravel-Excel

I have a problem to skip the row about importing excel laravel with the Maatwebsite / Laravel-Excel package.
I tried many ways from the internet but it still didn't work.
this is my controller code
if ($request->hasFile('file')) {
$import = new HsatuImport();
$file = $request->file('file'); //GET FILE
// config(['excel.import.startRow' => 2]);
Excel::import($import, $file)->limit(false, 2); //IMPORT FILE
return redirect()->route('admin.hsatus.upload')->withFlashSuccess('Upload Berhasil '.$import->getRowCount().' Data');
} else {
return redirect()->route('admin.hsatus.upload')->withFlashSuccess('Upload Gagal');
}
and this is my import code
<?php
namespace App\Imports;
use App\Models\Hsatu;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\ToModel;
class HsatuImport implements ToModel
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
private $rows = 0;
public function model(array $row)
{
++$this->rows;
return new Hsatu([
'region' => #$row[0],
'nomor_faktur' => #$row[1],
'nomor_rangka' => #$row[2],
'kode_mesin' => #$row[3]
]);
}
public function headingRow(): int
{
return 1;
}
public function getRowCount(): int
{
return $this->rows;
}
}
I had the problem with skipping when there's already existing Eloquent model. So below my code:
public function model(array $row)
{
$name = $row['name'];
if (!Category::where('name', $name)->exists())
return new Category([
'name' => $name
]);
}
I'm returning Model instance only if given statement is true.

Laravel get data from db array not working

When I run the code I get no error but the data I am trying to display is not displaying it's just blank.. can someone tell me what I'm doing wrong?
My controller:
public function openingPage($id) {
$this->getGames();
$games = $this->getGames();
return view('caseopener')->with('games',$games);
}
private function getGames() {
$games = array();
foreach ($this->data->items as $item) {
$game = new Game($item);
$games[] = array(
'id' => $game['id'],
'name' => $game['name'],
'price' => $game['price'],
'image' => $game['image'],
);
}
return $games;
}
The 'Game' Model that is used in 'getGames function':
class Game extends Model
{
private $id;
public $data;
public function __construct($id) {
parent::__construct();
$this->id = $id;
$this->data = $this->getData();
}
private function getData() {
$game = DB::table('products')->where('id', 1)->first();
if(empty($game)) return array();
return $game;
}
}
The view:
#foreach ($games as $game)
<div class="gold">$ {{ $game['price'] }}</div>
#endforeach
I think you are over-complicating things. You could simplify your flow like this:
Given your provided code, it seems like you are using a custom table name ('products') in your Game model. So we'll address this first:
Game.php
class Game extends Model
{
protected $table = 'products'; //
}
Now, it seems like you're searching an array of Game ids ($this->data->items). If so, you could make use of Eloquent for your query, specially the whereIn() method:
YourController.php
public function openingPage($id)
{
$games = Game::whereIn('id', $this->data->items)->get();
return view('caseopener')->with('games', $games);
}
Optionally, if you want to make sure of just returning the id, name, price and image of each Game/product, you could format the response with API Resources:
php artisan make:resource GameResource
Then in your newly created class:
app/Http/Resources/GameResource.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class GameResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
'image' => $this->image,
];
}
}
So now just update your controller:
YourController.php
use App\Http\Resources\GameResource;
public function openingPage($id)
{
$games = Game::whereIn('id', $this->data->items)->get();
return view('caseopener')->with('games', GameResource::collection($games));
} // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

MongoDB only works when using fetch via other function

I am trying to get a record from my MongoDB. To get the record I use the following code;
public function getEventsForAggregate($identifier)
{
$events = $this->MongoCollection()->findOne([
'_id' => $identifier
], [
'events',
]);
var_dump($events);
}
Unfortunately it dies on the findOne.
Do I change the code so the findOne is in a protected function it does work.
So the following code does work.
public function getEventsForAggregate($identifier)
{
$events = $this->getEvents($identifier);
var_dump($events);
}
protected function getEvents($identifier)
{
return $this->MongoCollection()->findOne([
'_id' => $identifier
], [
'events',
]);
}
Can some one explain how it is possible that the first code breaks, but the second one works?
Extra code;
/** #var MongoCollection */
protected $mongoCollection;
public function __construct(MongoCollection $MongoCollection)
{
$this->mongoCollection = $MongoCollection;
}
/**
* #return MongoCollection
*/
protected function MongoCollection()
{
return $this->mongoCollection;
}

Categories