onfailure download in laravel maatwebsite - php

public function onFailure(\Maatwebsite\Excel\Validators\Failure ...$failures)
{
$data = [];
foreach ($failures as $failure) {
$data[] = [
'row' => $failure->row(),
'attribute' => $failure->attribute(),
'values' => json_encode($failure->values()),
'errors' => json_encode($failure->errors()),
'module' => 'User',
];
}
dd($data);
Excel::download(new FailureExportPI($data),'failure_imports.xlsx');
}
i am trying to handle on failure items and download them in excel file but it is not working. when i die dump dd($data) i get the items but the issue is when i pass the data to download nothing happens my export is as below
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromView;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
class FailureExportPI implements FromView,ShouldAutoSize
{ public function __construct($data)
{
$this->data=$data;
// dd($this->data);
}
public function view(): View
{
return view('mfiintpi.error',['data'=>$this->data]);
}
}
what am i doing wrong?

Related

Laravel PhpSpreadsheet Multiple Table Import

i want to ask, is it possible to import excel excel to import
to the database like database table in php laravel?
of course there is a excelent package for import and export data from excel
Laravel-Excel
here is an example for export excel
class PermissionExport implements FromCollection, ShouldQueue , WithMapping , WithHeadings, WithEvents
{
public function registerEvents(): array
{
return [
BeforeSheet::class =>function(BeforeSheet $event){
$event->getDelegate()->setRightToLeft(true);
}
];
}
public function collection()
{
return Permission::all();
}
public function map($permissions): array
{
return [
$permissions->name,
$permissions->label,
];
}
public function headings(): array
{
return [
'permission name',
'permission description',
];
}
}
and here is and example for import data from excel
class PermissionsImport implements ToModel,WithStartRow
{
/**
* #param Collection $collection
*/
public function model(array $row)
{
return new permission([
'name' => $row[0],
'label' => $row[1],
]);
}
public function startRow(): int
{
return 2;
}
}

error handling failed in laravel excel and queue

I have tried to import csv using laravel excel and queue.I have tested import working without implement queue.its working perfectly.I was validate all rows before uploading csv.If validation error a mail will send to admin.Everything working fine without using queue.When i was using queue if no validation error it working.But if import function return validation error, error handling not working.it not hit the catch section.i checked the failed job.In exception column getting "maatwebsite\Excel\Validators\ValidationException: The given data was invalid. in C:\xampp\htdocs\user_import\vendor\maatwebsite\excel\src\Validators\RowValidator.php:68......".I dont know why error handling is not working in queue running.
controller
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ImportUser;
use App\Http\Requests\UserImportRequest;
use App\Events\ImportFailEvent;
class UserImportController extends Controller
{
public function import(UserImportRequest $request)
{
try{
Excel::import(new ImportUser, $request->file('file'));
} catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
$failures = $e->failures();
$failer_array = [];
foreach ($failures as $failure) {
$failer_array[] = $failure->errors()[0].$failure->row();
}
//send mail
event(new ImportFailEvent($failer_array));
}
}
}
import user
namespace App\Imports;
use App\Models\ImportedUser;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Illuminate\Contracts\Queue\ShouldQueue;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\WithValidation;
class ImportUser implements ToCollection,WithValidation,WithHeadingRow,WithBatchInserts, WithChunkReading, ShouldQueue
{
public function rules(): array
{
return [
'user_code' => 'required|regex:/^[a-bA-B0-9 ]+$/',
'user_name' => 'required',
'user_address' => 'required',
];
}
public function customValidationMessages()
{
return [
'user_code.required' => 'User Code is missing at row ',
'user_code.regex' => 'User Code contains symbols at row ',
'user_name.required' => 'User Name is missing at row ',
'user_address.required' => 'User Address is missing at row ',
];
}
public function collection(Collection $rows)
{
foreach ($rows as $row)
{
ImportedUser::create([
'user_code' => $row['user_code'],
'user_name' => $row['user_name'],
'user_address' => $row['user_address'],
]);
}
}
public function batchSize(): int
{
return 500;
}
public function chunkSize(): int
{
return 500;
}
}

how to return variable in excel import

I need to return to controlling the id of the products entered by the excel import.
ProductImport.php
<?php
namespace App\Imports;
use App\Product;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
class ProductImport implements ToCollection {
public function collection(Collection $rows) {
foreach ($rows as $row) {
$product = Product::create([
'name' => $row[0],
'detail' => $row[1]
])->id;
}
return $product;
}
}
ProductController.php
public function uploadProducts(Request $request) {
$request->validate([
'import_file' => 'required|file|mimes:xls,xlsx'
]);
$path = $request->file('import_file');
$import = new ProductImport;
Excel::import($import, $path);
//Here, how can I return the id of the products that were entered?
return response()->json(['message' => 'uploaded successfully'], 200);
}
I have not found a way to return variables in excel import. Thanks for your help.
You can do this by public variable of ProductImport class and then use it in your Controller.
First, create one public variable $product_ids in Import class, assign it all ids
class ProductImport implements ToCollection
{
public $product_ids; // declare one public variable
public function collection(Collection $rows)
{
foreach ($rows as $row) {
// store created product ids as array
$this->product_ids[] = Product::create([
'name' => $row[0],
'detail' => $row[1]
])->id;
}
return $product;
}
}
Now you can use the Import class variable in your Controller as below.
$import->product_ids;
Full code:
public function uploadProducts(Request $request)
{
$request->validate([
'import_file' => 'required|file|mimes:xls,xlsx'
]);
$path = $request->file('import_file');
$import = new ProductImport;
Excel::import($import, $path);
dd($import->product_ids); // it will return you an array
return response()->json(['message' => 'uploaded successfully'], 200);
}

Possible to add multiple parameters to excel import?

I have a basic form that contains an excel file upload and a select option.
The select contains a few options. I want to pass the selected option from the user with the file to my Excel::import
I tried passing another parameter to my import but it returns error. (has to be string, array given)
Is this possible using Laravel excel import?
Controller
public function create(Request $request)
{
if($request->hasFile('file'))
{
$package = $request->input('package');
// how can I add $package to my import to insert it to my user model?
Excel::import(new AccountsImport, $request->file('file'));
return ['message' => 'Excel has been succesfully uploaded'];
}
}
AccountsImport
class AccountsImport implements ToCollection, withHeadingRow
{
public function collection(Collection $rows)
{
$rows->each(function($row, $key) {
Account::create([
'name' => $row['student'],
'email' => $row['e_mail'],
// Want it to be possible to add my package here
//'package' => $package
]);
});
}
}
Maybe you could pass down custom data to your AccountsImport class?
You would have a data array as such:
$data = [
'package' => $package,
// other data here
];
You would then do something like this:
Excel::import(new AccountsImport($data), $request->file('file'));
That would require some changes in your import class.
class AccountsImport implements ToCollection, withHeadingRow
{
private $data;
public function __construct(array $data = [])
{
$this->data = $data;
}
public function collection(Collection $rows)
{
$rows->each(function($row, $key) {
Account::create(array_merge([
'name' => $row['student'],
'email' => $row['e_mail'],
// Want it to be possible to add my package here
//'package' => $package
], $this->data));
});
}
}
I took a look at Laravel Excel's API and couldn't see something that would cater for this, but this should work.

How to save array of objects to mysql database in laravel?

I am using vue with laravel. I am trying to save array of objects but not able to do it though i am able to save single object. Here is my code
App.vue
// Not working
saveData(){
this.axios.post('/addperson', **this.rows**).then((response) => {
console.log("WOW");
})
}
//working
saveData(){
this.axios.post('/addperson', **this.rows[0]**).then((response) => {
console.log("WOW");
})
}
Here is controller code where i am getting error when i pass array.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\OrderPerson;
class PersonController extends Controller
{
public function create(Request $request){
$person = new Person([
'name' => $request->get('name'),
'age' => $request->get('age'),
'user_id' =>$request->get('user_id')''
]);
$person->save();
return response()->json('Successfully added');
}
}
Can any body help me to save the array?
First of all assign all the this.rows to a data set then push it to the axios call something like this:
saveData(){
const postData = {
data: this.rows
}
this.axios.post('/addperson', postData).then((response) => {
console.log("WOW");
})
}
Now in laravel controller you can use foreach to use this data set.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\OrderPerson;
class PersonController extends Controller
{
public function create(Request $request){
foreach($request->data as $data)
{
$container = new Person([
'name' => $data['name'],
'age' => $data['age'],
'user_id' => $data['user_id']
]);
$container->save();
}
return response()->json('Successfully added');
}
}
Hope this helps.

Categories