Laravel-excel cannot update records "WithUpserts" - not found - laravel

I'm trying to update database but i got this error:
Interface 'App\Imports\WithUpserts' not found
I can't understand where is mistake.
Everything from examples. My import class here:
namespace App\Imports;
use App\bmwprice;
use Maatwebsite\Excel\Concerns\ToModel;
class bmwimport implements ToModel, WithUpserts
{
public function model(array $row)
{
return new bmwprice([
'NUMBER' => $row[0],
'NUMBER2' => $row[1],
'WEIGHT' => $row[2],
'VPE' => $row[3],
'VIN' => $row[4],
'NL' => $row[5],
'TITLE' => $row[6],
'TEILEART'=> $row[7],
]);
}
public function uniqueBy()
{
return 'NUMBER';
}
}
Thank you.

Add
use Maatwebsite\Excel\Concerns\WithUpserts; // below other imports using use

<?php
namespace App\Imports;
use App\Models\CatalogStore;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithUpserts;
class CatalogupdateImport implements ToModel, WithUpserts
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new CatalogStore([
'sku' => $row['sku'],
'price' => $row['price'],
'qty' => $row['qty'],
]);
}
/**
* #return string|array
*/
public function uniqueBy()
{
return 'price';
}
}
I need to update the price field in an existing table but I get an error in my code that I can't find. Even if I remove sku in it goes to the next field "qty" and it generates undefined.
"Undefined index: sku"

Related

Validation in Fast Excel package Laravel

ImportController
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Talent\ImportData\Requests\ImportDataRequest;
use Illuminate\Support\Facades\Hash;
use Rap2hpoutre\FastExcel\FastExcel;
class ImportController extends Controller
{
public function __construct(private User $user)
{
}
public function import(ImportDataRequest $request)
{
$validated = $request->validated();
$collection = (new FastExcel)->import($validated['file'], function ($rows) {
$user = $this->user->create([
'name' => $rows['First Name'] . " " . $rows['Last Name'],
'email' => $rows['Email'],
'password' => Hash::make('Introcept#123'),
'role' => $rows['Role']
]);
$employee = $user->employees()->create([
'status' => $rows['Status'],
'first_name' => $rows['First Name'],
'last_name' => $rows['Last Name'],
'email' => $rows['Email'],
'contact_number' => $rows['Contact Number'],
'date_of_birth' => $rows['Date of Birth'],
'current_address' => $rows['Current Address'],
'pan_number' => $rows['Pan Number'],
'bank_account_number' => $rows['Bank Account Number'],
]);
$education = $employee->education()->create([
'education_level' => $rows['Education Level'],
'passed_year' => $rows['Passed Year'],
'institution' => $rows['Institution'],
]);
$employment = $employee->employment()->create([
'organization' => $rows['Organization'],
'join_date' => $rows['Join Date'],
'current_position' => $rows['Current Position'],
'work_schedule' => $rows['Work Schedule'],
'team' => $rows['Team'],
'manager' => $rows['Manager'],
'superpowers' => $rows['Superpower'],
]);
$employment->manages()->create([
'employee_id' => $rows['Manages'],
]);
});
}
}
ImportData Request
<?php
namespace App\Talent\ImportData\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ImportDataRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array<string, mixed>
*/
public function rules()
{
return [
'file'=>'required|mimes:csv,xlsx'
];
}
}
I am creating an API where the admin can import data from an excel file. Here, I am using the Fast Excel package in order to import data. Everything is working fine, but I have no idea how I can validate excel data before saving it into the database. I am pretty new to Laravel and any help will be really appreciated. Thank you

Update a record of DB if it exists after importing a Csv file in Laravel?

I'm using Maatwebsite\Excel to import a csv file to store new users in the DB. If i have already a record in DB with the same data it creates and error. How can i update the record if it exists ?
My import class is :
class UsersImport implements ToModel, WithCustomCsvSettings, WithHeadingRow
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new User([
'firstname' => $row['firstname'],
'lastname' => $row['lastname'],
'email' => $row['email'],
'password' => $row['pass'],
'created_at' => $row['registered'],
]);
}
public function getCsvSettings(): array
{
return [
'delimiter' => ","
];
}
}
You should implement the WithUpserts interface. Also you need to specify which field should be unique so if it exists, it will update the record, else it will create new one.
Assuming your unique column is email, change your code to the following:
class UsersImport implements ToModel, WithCustomCsvSettings, WithHeadingRow, WithUpserts
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new User([
'firstname' => $row['firstname'],
'lastname' => $row['lastname'],
'email' => $row['email'],
'password' => $row['pass'],
'created_at' => $row['registered'],
]);
}
public function getCsvSettings(): array
{
return [
'delimiter' => ","
];
}
public function uniqueBy()
{
return 'email';
}
}

Laravel-Excel returns required error with all rows

I am implementing Laravel-Excel into my project and could not figure out the validation.
I try to upload the xlsx file with one row of data in it but still, the import throws required error.
Following is my EventResultImport code
namespace App\Imports;
use App\Models\Data\EventResult;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;
class EventResultImport implements ToModel, WithValidation, WithHeadingRow
{
use Importable;
public function model(array $row)
{
HeadingRowFormatter::default('none');
return new EventResult([
'event_id' => $row[0],
'event_name' => $row[1],
]);
}
public function rules(): array
{
return [
//'EventId' => 'required|numeric', Tried this
//'*.EventId' => 'required|numeric', Tried this
'0' => 'required|numeric'
];
}
}
I get error on second-row event if there is numeric data in column EventId.
Thank you
You are implementing WithHeadingRow, so the attributes must match:
public function rules(): array
{
return [
'event_id' => 'required|numeric'
];
}
To skip nulls:
public function model(array $row)
{
if (!isset($row[0])) {
return null;
}
return new User([
'name' => $row[0],
]);
}

how to set cakephp 3 email unique validation

I created a table users with 2 fields id(primary),(email)
I want email unique validation used following code but not working only not empty working.
<?php
namespace App\Controller;
use App\Model\Validation\UserValidator;
class UsersController extends AppController
{
public function register()
{
$this->loadModel("users");
if ($this->request->is('post')) {
$validator = new UserValidator();
$errors = $validator->errors($this->request->getData());
if (empty($errors)) {
} else {
$this->set('errors', $errors);
}
}
}
}
src/Model/Validation/UserValidator.php
<?php
namespace App\Model\Validation;
use Cake\Validation\Validator;
use Cake\ORM\Table;
use Cake\ORM\Rule\IsUnique;
class UserValidator extends Validator {
public function __construct()
{
parent::__construct();
$this
->notEmpty('name', 'The name field cannot be left empty')
->notEmpty('email', 'Fill Valid Email Id')
->add('email',['unique' => ['rule' => 'validateUnique', 'provider' => 'table', 'message' => 'Not unique']])
->notEmpty('mobile', 'Fill Valid 10 Digit Mobile No.');
}
}
create this file under \src\Model\Table\Userstable.php
updated
change the the filename capitalize the to make it \src\Model\Table\UsersTable.php
in my code below I validated my username and email as unique
use App\Model\Entity\User;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\ORM\Rule\IsUnique;
/**
* Users Model
*
*/
class UsersTable extends Table
{
/**
* Initialize method
*
* #param array $config The configuration for the Table.
* #return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->table('users');
}
/**
* Default validation rules.
*
* #param \Cake\Validation\Validator $validator Validator instance.
* #return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->requirePresence('username','create')
->notBlank('username', 'A username is required')
->add('username', 'unique', [
'rule' => 'validateUnique',
'provider' => 'table',
'message' => 'Username is already used'
]);
$validator
->requirePresence('email','create')
->notBlank('email', 'An email is required')
->add('email', 'unique', [
'rule' => 'validateUnique',
'provider' => 'table',
'message' => 'Email is already used'
]);
return $validator;
}
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(['username']));
$rules->add($rules->isUnique(['email']));
return $rules;
}
}

How to build rule exist in or equal to a number in cakephp 3?

I have table comments with column parent_id.
And this is content of CommentsTable.php:
namespace App\Model\Table;
use App\Model\Entity\Comment;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
/**
* Comments Model
*/
class CommentsTable extends Table
{
/**
* Initialize method
*
* #param array $config The configuration for the Table.
* #return void
*/
public function initialize(array $config)
{
$this->table('comments');
$this->displayField('id');
$this->primaryKey('id');
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Posts', [
'foreignKey' => 'post_id',
'joinType' => 'INNER'
]);
$this->belongsTo('ParentComments', [
'className' => 'Comments',
'foreignKey' => 'parent_id'
]);
$this->hasMany('ChildComments', [
'className' => 'Comments',
'foreignKey' => 'parent_id'
]);
}
/**
* Default validation rules.
*
* #param \Cake\Validation\Validator $validator Validator instance.
* #return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->allowEmpty('id', 'create')
->requirePresence('body', 'create')
->notEmpty('body')
->requirePresence('path', 'create')
->notEmpty('path')
->add('status', 'valid', ['rule' => 'numeric'])
->requirePresence('status', 'create')
->notEmpty('status')
->add('created_at', 'valid', ['rule' => 'datetime'])
->requirePresence('created_at', 'create')
->notEmpty('created_at')
->add('updated_at', 'valid', ['rule' => 'datetime'])
->requirePresence('updated_at', 'create')
->notEmpty('updated_at');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* #param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* #return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['user_id'], 'Users'));
$rules->add($rules->existsIn(['post_id'], 'Posts'));
$rules->add($rules->existsIn(['parent_id'], 'ParentComments'));
return $rules;
}
}
I want to build rule for field parent_id: exist in ParentComments or equal to 0.
Can you help me?
Thank you very much.
Rules are just callable functions or callable classes. The existsIn() function is just an alias for the ExistsIn class. We can use the to our advantage:
...
use Cake\ORM\Rule\ExistsIn;
class CommentsTable extends Table
{
...
public function buildRules(RulesChecker $rules)
{
...
$rules->add(
function ($entity, $options) {
$rule = new ExistsIn(['parent_id'], 'ParentComments');
return $entity->parent_id === 1 || $rule($entity, $options);
},
['errorField' => 'parent_id', 'message' => 'Wrong Parent']
);
return $rules;
}
}

Resources