Undefined index: code use Export to Excel in Laravel 5.8 - excel

I'm executing Export, Import to Excel in Laravel. But I have an error
Undefined index: code
in a file AlumniImport.php.
Thank you for help!
AlumniImport.php
namespace App\Imports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Illuminate\Support\Facades\Hash;
class AlumniImport implements ToModel
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new User([
'code' => $row["code"],
'first_name' => $row["first_name"],
'last_name' => $row["last_name"],
'username' => $row["username"],
'password' => Hash::make($row["password"]),
'tel' => $row["tel"],
'email' => $row["email"],
'gender' => $row["gender"],
'birthday' => $row["birthday"],
'address' => $row["address"],
'status_id' => $row["status_id"],
]);
}
}
AlumniController.php
// Excel
use App\Imports\AlumniImport;
use App\Exports\AlumniExport;
use Excel;
class AlumniController extends Controller
{
public function import()
{
Excel::import(new AlumniImport,request()->file('file'));
return back();
}
}
Example of data in Excel:
code first_name last_name username password tel email gender birthday address status_id
B8888 John Smith johnsmith 123456 123456 johnsmith#gmail.com Male 4/9/1998 USA 1
B7777 Tom Cruise tomcruise 123456 123456 tomcruies#gmail.com Male 4/5/1998 Canada 1
B6666 Lena Do lenado 123456 123456 lenado#gmail.com Male 9/4/1997 USA 2

You can confirm my suggestion by doing a var_dump($row);die();
what i found on the package Maatwebsite, the $row has numeric indexes.
try this
class AlumniImport implements ToModel
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new User([
'code' => $row[0],
'first_name' => $row[1],
'last_name' => $row[2],
'username' => $row[3],
'password' => Hash::make($row[4]),
'tel' => $row[5],
'email' => $row[6],
'gender' => $row[7],
'birthday' => $row[8],
'address' => $row[9],
'status_id' => $row[10],
]);
}
}
-----edit-----
dont forget to put the fields in the $fillable of the User::class
class User extend Model
{
protected $fillable = ['code','first_name', 'last_name', 'username', 'password', 'tel', 'email', 'gender', 'birthday', 'address', 'status_id'];
.....
}
if you dont wanna put these fields as fillable and i dont recommend you to do it (especially for the password field) you can do it this way;
class AlumniImport implements ToModel
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
$user = new User();
$user->code = $row[0];
$user->first_name = $row[1];
$user->last_name = $row[2];
$user->username = $row[3];
$user->password = Hash::make($row[4]);
$user->tel = $row[5];
$user->email = $row[6];
$user->gender = $row[7];
$user->birthday = $row[8];
$user->address = $row[9];
$user->status_id = $row[10];
return $user;
}
}

Add this line in your AlumniImport class:
use Maatwebsite\Excel\Concerns\WithHeadingRow;
After this, include WithHeadingRow in your AlumniImport class like this:
class AlumniImport implements ToModel,WithHeadingRow

Related

How to import products with variations in Shopware 6

I'm trying to import products from an XML with variations.
The import for the products works so far but it doesn't create the variations.
Here is my code (simplified):
/**
* #return int
* #throws \Exception
*/
public function execute()
{
// avoid reaching memory limit
ini_set('memory_limit', '-1');
// set tax id
$this->setTaxId();
if (empty($this->taxId)) {
return 1;
}
// read products from import xml file
$importProducts = $this->loadProducts();
$csvBatch = array_chunk($importProducts, self::BATCH);
$productNumbers = [];
foreach ($csvBatch as $products) {
$productNumbers[] = $this->processImportProducts($products, false);
}
$this->deleteProducts(array_merge(...$productNumbers));
return 0;
}
/**
* #param $productsData
* #param $progressBar
* #return array
*/
private function processImportProducts($productsData, $progressBar)
{
$products = [];
$productNumbers = [];
foreach ($productsData as $product) {
$products[$product['SKU']['#cdata']] = $this->importProducts($product, $progressBar);
$productNumbers[] = $product['SKU']['#cdata'];
}
// upsert product
try {
$this->cleanProductProperties($products, $this->context);
$this->productRepository->upsert(array_values($products), $this->context);
} catch (WriteException $exception) {
$this->logger->info(' ');
$this->logger->info('<error>Products could not be imported. Message: '. $exception->getMessage() .'</error>');
}
unset($products);
return $productNumbers;
}
/**
* #param $product
* #param $progressBar
* #return array
*/
private function importProducts($product, $progressBar)
{
...
$productData = [
'id' => $productId,
'productNumber' => $productNumber,
'price' => [
[
'currencyId' => Defaults::CURRENCY,
'net' => !empty($product['net']) ? $product['net'] : 0,
'gross' => !empty($product['net']) ? $product['net'] : 0,
'linked' => true
]
],
'stock' => 99999,
'unit' => [
'id' => '3fff95a8077b4f5ba3d1d2a41cb53fab'
],
'unitId' => '3fff95a8077b4f5ba3d1d2a41cb53fab',
'taxId' => $this->taxId,
'name' => $productNames,
'description' => $productDescriptions
];
if(isset($product['Variations'])) {
$variationIds = $product['Variations']['#cdata'] ?? '';
$productData['variation'] = [$this->getProductVariationIds($variationIds)];
}
return $productData;
}
/**
* Get product variation ids
*
* #param string $productVariations
* #return string
*/
private function getProductVariationIds($productVariations)
{
$productVariationIds = explode(',', $productVariations);
// get product variationIds in form of a string list
$ids = $this->productRepository->search(
(new Criteria())->addFilter(new EqualsAnyFilter('productNumber', $productVariationIds)),
$this->context
)->getIds();
return implode(',', $ids);
}
It loads correctly the ids but nothing happen. Also no error.
Anyone an idea how to import variations as well?
The variation field is not meant to be persisted or to create variants of a product. It has the Runtime flag, meaning it's not an actual database column but processed during runtime.
You have to create/update variants just like you create the parent product. Additionally you have to set the parentId and the options. The latter being associations to property_group_option, which you'll have to create first.
So in addition to your existing payload when creating parent products, you'll have to add this data to the variants:
$productData = [
// ...
'parentId' => '...'
'options' => [
['id' => '...'],
['id' => '...'],
['id' => '...'],
// ...
],
];
Finally you'll have to create the product_configurator_setting records. That's one record for each option used across all variants. Also the productId for the records has to be the one of the parent product.
$repository = $this->container->get('product_configurator_setting.repository');
$configuratorSettings = [];
foreach ($options as $option) {
$configuratorSetting = [
'optionId' => $option['id'],
'productId' => $parentId,
];
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('productId', $parentId));
$criteria->addFilter(new EqualsFilter('optionId', $option['id']));
$id = $repository->searchIds($criteria, $context)->firstId();
// if the configurator setting already exists, update or skip
if ($id) {
$configuratorSetting['id'] = $id;
}
$configuratorSettings[] = $configuratorSetting;
}
$repository->upsert(configuratorSettings, $context);
Just as an addition to make things easier. When creating a product with variants you can just update the configuratorSettings of the parent/father/main-product (whatever you call it).
Then Shopware6 will go and create the variant products automatically. Also the uuids of the children are created automatically. So if need to keep track of these you have to query them after the creation process.
But for a fast creation this might be much faster, if you have a lot of variants the only "variation" are the options. So no special images or texts.

Import excel in laravel Array key

I am trying to upload the file but when I give import I get the following error Undefined array key "idEvento"
When I handle it by number that I start from scratch I do not get any error and insert into the database
Event Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Eventos extends Model
{
use HasFactory;
protected $fillable = [
'nombre',
'idEvento',
'idSede',
'inicio',
'fin',
'idModalidad',
'cupo',
'valor',
];
}
Import data function
public function importData(Request $request){
$file = $request->file('documento');
$validator = Validator::make(
array(
'file' => $file,
),
array(
'file' => 'file|max:5000|mimes:xlsx,xls',
)
);
if ($validator->fails()) {
return Redirect::to('conferencia/import');
}
$import = new EventosImport();
Excel::import($import, request()->file('documento'));
return view('conferencias.import', ['numRows'=>$import->getRowCount()]);
//return redirect()->to(url('conferencia'));
}
Event import code
<?php
namespace App\Imports;
use App\Models\Eventos;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class EventosImport implements ToModel, WithHeadingRow
{
private $numRows = 0;
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
++$this->numRows;
return new Eventos([
'nombre' => $row['nombre'],
'idEvento' => $row['idEvento'],
'idSede' => $row['idSede'],
'inicio' => \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row['inicio']),
'fin' => \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row['fin']),
'idModalidad' => $row['idModalidad'],
'cupo' => $row['cupo'],
'valor' => $row['valor'],
]);
}
public function getRowCount(): int
{
return $this->numRows;
}
}
Image of the excelenter image description here
it´s better than you use your function import in your controller instead of in your model. To read excel use sometimes similary to:
$data = Excel::load($path, function($reader) {})->get();
if(!empty($data) && $data->count()){
foreach ($data->toArray() as $key => $value) {
if(!empty($value)){
foreach ($value as $v) {
$insert[] = ['title' => $v['title'], 'description' => $v['description']];
}
}
}
if(!empty($insert)){
Item::insert($insert);
return back()->with('success','Insert Record successfully.');
}
}

google socialite laravel 8 return after authentication a blank screen

when i am tring to authenticate with google account it returns an empty string i don't know why so can u help me find this error i made the all steps requiring to do the authentication it returns callback with an empty string and my client_id and client secret are correct
here is my code google controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use Exception;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
class GoogleController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function redirectToGoogle()
{
return Socialite::driver('google')->redirect();
}
/**
* Create a new controller instance.
*
* #return void
*/
public function handleGoogleCallback()
{
try {
$user = Socialite::driver('google')->user();
$finduser = User::where('social_id', $user->id)->first();
if($finduser){
Auth::login($finduser);
return redirect()->intended('dashboard');
}else{
$newUser = User::create([
'name' => $user->name,
'email' => $user->email,
'social_id'=> $user->id,
'social_type'=> 'google',
'password' => encrypt('123456dummy')
]);
Auth::login($newUser);
return redirect()->intended('dashboard');
}
} catch (Exception $e) {
dd($e->getMessage());
}
}
}
and my routes
<?php
use Illuminate\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 () {
return view('welcome');
});
Route::middleware([
'auth:sanctum',
config('jetstream.auth_session'),
'verified'
])->group(function () {
Route::get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
});
Route::get('auth/google', [App\Http\Controllers\GoogleController::class, 'redirectToGoogle']);
Route::get('auth/google/callback', [App\Http\Controllers\GoogleController::class, 'handleGoogleCallback']);
my config/services.php
'google' => [
'client_id' => '982061662199-bns94j425f1cgq7p8b0eo4lctjn83e4e.apps.googleusercontent.com',
'client_secret' => 'GOCSPX-9AFn2bhebi2yPUpCU8_LIzfb',
'redirect' => 'http://localhost:8000/auth/google/callback',
],

Friends of Cake search: hasmany associations

I seem to recall far better documentation the last time I used it. I need to be able to search across multiple tables, finding Locations which have ShippingAddresses that match search criteria. Here are my Location model showing the association between the Addresses table and Locations table:
class LocationsTable extends Table
{
/**
* Initialize method
*
* #param array $config The configuration for the Table.
* #return void
*/
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('locations');
$this->setDisplayField('name');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->addBehavior('Search.Search');
// Stores:
$this->belongsTo('Stores', [
'foreignKey' => 'store_id',
]);
// Shipping addresses:
$this->hasMany('ShippingAddresses', [
'foreignKey' => 'location_id',
'className' => 'Addresses',
'dependent' => true,
])->setConditions(['type' => 'shipping']);
// Billing addresses
$this->hasMany('BillingAddresses', [
'foreignKey' => 'location_id',
'className' => 'Addresses',
'dependent' => true,
])->setConditions(['type' => 'billing']);
// Deliverables
$this->belongsToMany('Deliverables', [
'through' => 'LocationsDeliverables',
]);
}
/**
* Default validation rules.
*
* #param \Cake\Validation\Validator $validator Validator instance.
* #return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator): Validator
{
$validator
->integer('id')
->allowEmptyString('id', null, 'create');
$validator
->scalar('name')
->maxLength('name', 255)
->requirePresence('name', 'create')
->notEmptyString('name');
$validator
->scalar('identifier')
->maxLength('identifier', 255)
->allowEmptyString('identifier');
$validator
->scalar('description')
->allowEmptyString('description');
return $validator;
}
/**
* Returns a summarized set of important data.
*
* #param \Cake\ORM\Query $query The current query
* #param array $options An array of options.
* #return \Cake\ORM\Query
*/
public function findSummary(Query $query, array $options): Query
{
// do things.
return $query
->where(['Locations.id' => $options['location_id']])
->contain(
'Deliverables',
function (Query $q) {
return $q
->select(['id', 'parent_id', 'name', 'description'])
->where(['LocationsDeliverables.default_quantity >' => 0]);
}
)
->contain(['ShippingAddresses', 'Stores']);
}
}
Here is the search function call in context in the Locations controller:
/**
* Index method
*
* #return \Cake\Http\Response|null|void Renders view
*/
public function index()
{
$this->Authorization->skipAuthorization();
$locations = $this->paginate($this->Locations, [
'contain' => ['Stores', 'ShippingAddresses'],
'finder' => [
'search' => ['search' => $this->request->getQueryParams()],
],
]);
$this->set(compact('locations'));
}
According to the information provided in this comment, you should just be able to add the additional ShippingAddress columns to the search collection in it's dot-noted version. But of course, hasMany associations are queried by CakePHP as a separate operation, so doing so fails:
class LocationsCollection extends FilterCollection
{
/**
* #return void
*/
public function initialize(): void
{
$this->like('name')
->value('identifier')
->value('store_id')
->add('q', 'Search.Like', [
'before' => true,
'after' => true,
'fieldMode' => 'OR',
'comparison' => 'LIKE',
'wildcardAny' => '*',
'wildcardOne' => '?',
'fields' => ['name', 'description', 'Stores.store_name', 'ShippingAddresses.street_1'],
]);
}
}
Using this search, I get the error message "Column not found: 1054 Unknown column 'ShippingAddresses.street_1' in 'where clause'". That makes sense, because that's not how hasMany associations work. But then, how DO I query this data?
Thanks for your help!

error in codeigniter 4 You must set the database table to be used with your query

i am working codeigniter 4. i am trying to fetch data from database by creating method in Model but am getting error
You must set the database table to be used with your query
even I have mentioned the table name in query builder. i dun know why this is happening ? following is my code
public function Login($values)
{
$db = \Config\Database::connect();
$result= $db->table('tbl_adminuser')
->where(['username',$values['username']])
->where(['password',$values['password']])
->get()
->getResult();
print_r($result);
}
There are two types of getting data from the database.
Using the Model file
Load db in the controller file
Check both the below types to get data from the database.
1. Using the Model file
First, create a User model and mention the name of the database table.
Here is the sample of model file:
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserMasterModel extends Model
{
protected $table = 'user_master';
}
Then create a controller file and load the model using use App\Models\UserMasterModel;.
You should following the below sample of the controller file there is mention load the model and get the data using a model file.
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\UserMasterModel;
public function __construct()
{
$this->db = \Config\Database::connect();
}
public function Login($values){
$UserMasterModel = new UserMasterModel();
$result = $UserMasterModel->where('username',$values['username'])
->where('password',$values['password'])
->findAll();
print_r($result);
}
2. Load db in controller file
When using \Config\Database::connect() the controller file looks like below:
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
public function __construct()
{
$this->db = \Config\Database::connect();
$this->user_master = $this->db->table('user_master');
}
public function Login($values){
$this->user_master->select('*');
$this->user_master->where('username',$values['username']);
$this->user_master->where('password',$values['password']);
$result = $this->user_master->get()->getResult();
print_r($result);
}
create model for users
<?php namespace Myth\Auth\Models;
use CodeIgniter\Model;
use Myth\Auth\Authorization\GroupModel;
use Myth\Auth\Entities\User;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $returnType = User::class;
protected $useSoftDeletes = false;
protected $allowedFields = [
'email', 'username', 'password_hash', 'reset_hash', 'reset_at', 'reset_expires', 'activate_hash',
'status', 'status_message', 'active', 'force_pass_reset', 'permissions',
'first_name',
'last_name',
'image',
'address',
'phone',
'email',
'gender',
'country',
'city',
'created_at',
'updated_at',
'deleted_at',
];
protected $useTimestamps = false;
protected $validationRules = [
'email' => 'if_exist|required|valid_email|is_unique[users.email,id,{id}]',
'phone' => 'if_exist|required|is_unique[users.phone,id,{id}]',
'username' => 'if_exist|required|alpha_numeric_punct|min_length[3]|max_length[30]|is_unique[users.username,id,{id}]',
'password_hash' => 'if_exist|required',
];
protected $validationMessages = [];
protected $skipValidation = false;
protected $afterInsert = ['addToGroup'];
/**
* The id of a group to assign.
* Set internally by withGroup.
*
* #var int|null
*/
protected $assignGroup;
/**
* Logs a password reset attempt for posterity sake.
*
* #param string $email
* #param string|null $token
* #param string|null $ipAddress
* #param string|null $userAgent
*/
public function logResetAttempt(string $email, string $token = null, string $ipAddress = null, string $userAgent = null)
{
$this->db->table('auth_reset_attempts')->insert([
'email' => $email,
'ip_address' => $ipAddress,
'user_agent' => $userAgent,
'token' => $token,
'created_at' => date('Y-m-d H:i:s')
]);
}
/**
* Logs an activation attempt for posterity sake.
*
* #param string|null $token
* #param string|null $ipAddress
* #param string|null $userAgent
*/
public function logActivationAttempt(string $token = null, string $ipAddress = null, string $userAgent = null)
{
$this->db->table('auth_activation_attempts')->insert([
'ip_address' => $ipAddress,
'user_agent' => $userAgent,
'token' => $token,
'created_at' => date('Y-m-d H:i:s')
]);
}
/**
* Sets the group to assign any users created.
*
* #param string $groupName
*
* #return $this
*/
public function withGroup(string $groupName)
{
$group = $this->db->table('auth_groups')->where('name', $groupName)->get()->getFirstRow();
$this->assignGroup = $group->id;
return $this;
}
/**
* Clears the group to assign to newly created users.
*
* #return $this
*/
public function clearGroup()
{
$this->assignGroup = null;
return $this;
}
/**
* If a default role is assigned in Config\Auth, will
* add this user to that group. Will do nothing
* if the group cannot be found.
*
* #param mixed $data
*
* #return mixed
*/
protected function addToGroup($data)
{
if (is_numeric($this->assignGroup)) {
$groupModel = model(GroupModel::class);
$groupModel->addUserToGroup($data['id'], $this->assignGroup);
}
return $data;
}
}
too use model
$model = new usermodel();
$model->asObject()->where('active', '1')->findAll();

Resources