I am getting the error defined in heading.
$data = Excel::import([], $path)->get(); //error
if($data->count() > 0)
{
foreach($data->toArray() as $key => $value)
{
foreach($value as $row)
{
$insert_data[] = array(
'email' => $row['email'],
'name' => $row['name'],
'report' => $row['report']
);
}
}
I also used the new UsersImport instead of empty array. I didn't get any solution regarding the get() function in Maatwebsite. What am i doing wrong.
I use laravel 8 & have 3 table:
Products, ProductPrice & ProductsPublisher:
this is my Products model for this relationship:
public function lastPrice(){
return $this->hasMany(ProductPrice::class)->where('status','active')->orderBy('created_at','DESC')->distinct('publisher_id');
}
and this is my productsPrice model for publisher relationship:
public function getPublisher(){
return $this->belongsTo(ProductsPublisher::class,'publisher_id');
}
now, i want to use laravel resource for my api, i wrote products resource:
public function toArray($request)
{
return [
'id' => $this->id,
'price' => lastPrice::make($this->lastPrice),
'status' => $this->status,
'slug' => $this->slug,
'title' => $this->title,
'description' => $this->description,
'txt' => $this->txt,
'lang' => $this->lang,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
but in lastPrice resource, when i wrote like this:
return [
'id' => $this->id,
'main_price' => $this->main_price
];
it give me this error:
Property [id] does not exist on this collection instance.
when i use this code:
return parent::toArray($request);
get response but because i need to use another relationship in my lastPirce for publishers, i cant use that code and should return separately my data.
What i should to do?
thanks
Edit 1:
this is my Controller Code:
$products = Product::where('id',$id)->where('slug',$slug)->where('status','confirm')->first();
if(!$products){
return $this->sendError('Post does not exist.');
}else{
return $this->sendResponse(new \App\Http\Resources\Products\Products($products), 'Posts fetched.');
}
and this is sendResponse & sendError:
public function sendResponse($result, $message)
{
$response = [
'success' => true,
'data' => $result,
'message' => $message,
];
return response()->json($response, 200);
}
public function sendError($error, $errorMessages = [], $code = 404)
{
$response = [
'success' => false,
'message' => $error,
];
if(!empty($errorMessages)){
$response['data'] = $errorMessages;
}
return response()->json($response, $code);
}
thanks.
Edit 2:
i change my lastPrice Resource toArray function to this and my problem solved, but i think this isn't a clean way, any better idea?
$old_data = parent::toArray($request);
$co = 0;
$new_data = [];
foreach ($old_data as $index){
$publisher_data = Cache::remember('publisher'.$index['publisher_id'], env('CACHE_TIME_LONG') , function () use ($index) {
return ProductsPublisher::where('id' , $index['publisher_id'])->first();
});
$new_data[$co]['main_prices'] = $index['main_price'];
$new_data[$co]['off_prices'] = $index['off_price'];
$new_data[$co]['publisher'] = SinglePublisher::make($publisher_data);
$new_data[$co]['created_at'] = $index['created_at'];
$co++;
}
return $new_data;
The amount I'm passing seems correct, but I got always an error.
As I checkout the amount is invalid, even if I'm passing a float, and this error is shown on the page after submit:
The payment function is as following:
public function payment(Request $request) {
$data = $request->all();
// dd($data['price']);
$gateway = new Braintree\Gateway([
'environment' => config('services.braintree.environment'),
'merchantId' => config('services.braintree.merchantId'),
'publicKey' => config('services.braintree.publicKey'),
'privateKey' => config('services.braintree.privateKey')
]);
$amount = Sponsorship::where('price', $data['price'])->first();
// dd($amount);c
$nonce = $request->payment_method_nonce;
$result = $gateway->transaction()->sale([
'amount' => $amount,
'paymentMethodNonce' => $nonce,
'customer' => [
'firstName' => 'Tony',
'lastName' => 'Stark',
'email' => 'tony#avengers.com',
],
'options' => [
'submitForSettlement' => true
]
]);
if ($result->success) {
$transaction = $result->transaction;
// header("Location: transaction.php?id=" . $transaction->id);
return back()->with('success_message', 'Transaction successful. The ID is:'. $transaction->id);
} else {
$errorString = "";
foreach ($result->errors->deepAll() as $error) {
$errorString .= 'Error: ' . $error->code . ": " . $error->message . "\n";
}
// $_SESSION["errors"] = $errorString;
// header("Location: index.php");
return back()->withErrors('An error occurred with the message: '.$result->message);
}
}
Here is my code in the controller.
I want multiple data to insert into a database but I have a problem with Array:
public function postCreate(Request $request)
{
$data = $request->all();
$lastid = Tr_header::create($data)->id;
if (count($request->id_product) > 0)
{
foreach($request->id_product as $item => $value)
$datax = array(
'id_tr_header' => $lastid,
'id_product' => $request->id_product[$item],
'qty' => $request->qty[$item],
'date_kembali' => $request->date_kembali[$item],
'information' => $request->information[$item],
);
Tr_detail::insert($datax);
}
return redirect()->back();
If you want to insert multiple row at a time try this:
{
$data = $request->all();
$lastid = Tr_header::create($data)->id;
if (count($request->id_product) > 0)
{
$datax = [];
foreach($request->id_product as $item => $value)
array_push($datax ,[
'id_tr_header' => $lastid,
'id_product' => $request->id_product[$item],
'qty' => $request->qty[$item],
'date_kembali' => $request->date_kembali[$item],
'information' => $request->information[$item],
]);
Tr_detail::insert($datax);
}
return redirect()->back();
You are overwritting your $datax variable, you need to create an array of arrays to pass on to your insert() function:
public function postCreate(Request $request)
{
$data = $request->all();
$lastid = Tr_header::create($data)->id;
if (count($request->id_product) > 0) {
$datax = [];
foreach ($request->id_product as $item => $value)
$datax[] = array(
'id_tr_header' => $lastid,
'id_product' => $request->id_product[$item],
'qty' => $request->qty[$item],
'date_kembali' => $request->date_kembali[$item],
'information' => $request->information[$item],
);
Tr_detail::insert($datax);
}
return redirect()->back();
}
I am trying to deploy a cakePHP app which works exactly as it should in Windows.
I use an LdapUser model to authenticate through Active Directory:
LdapUser:
<?php
class LdapUser extends AppModel
{
var $name = 'LdapUser';
var $useTable = false;
var $myCompany_ldap = "x.x.x.x";
//var $myCompany_ldap_config = array ('basedn' => 'CN=x,DC=x,DC=x');
var $basedn = 'CN=x,DC=x,DC=x';
var $myCompany_ldap_domain = "x.x";
// var $user = "x#x.x";
// var $pass = "x!";
var $exists = false;
var $ds;
function __construct()
{
parent::__construct();
ini_set('max_execution_time', 300); //300 seconds = 5 minutes
$this->ds=ldap_connect( $this->myCompany_ldap );
// print_r($this->basedn);
// debug($this->ds);
// print_r($this->ds);
ldap_set_option($this->ds, LDAP_OPT_PROTOCOL_VERSION, 3);
print_r($this->res);
//debug($this->exists);
//print_r($this->exists);
}
function __destruct()
{
ldap_close($this->ds);
// $this->loadModel('Cookie');
// $this->Cookie->destroy();
}
function isConnected(){
return ldap_bind($this->ds, $this->basedn);
}
function isLdapUser($user, $pass){
$this->exists = ldap_bind($this->ds, $user, $pass);
// debug($this->exists);
//debug($user);
// debug($pass);
return $this->exists;
}
}
And then in UserController inside login function:
// Login User
public function login() {
// Check if the user is already logged in
if ($this->Session->check('Auth.User.id')){
// Redirect to login page
$this->redirect($this->Auth->loginRedirect);
}
else{
// If the user is not logged in
session_set_cookie_params(0);
// If the request is a POST request
if ($this->request->is('post')) {
//get credentials
$this->username = $this->request->data['User']['username'];
$this->password = $this->request->data['User']['password'];
$this->domain = $this->request->data['User']['domain'];
//debug($this->username);
debug($this->domain) ;
if ($this->Auth->login() ) {
// Successful login
//Check if specific user exists in LDAP:
$this->loadModel('LdapUser');
$this->ds = $this->LdapUser->isConnected();
//print_r('Ldap status: '. $this->ds);
//debug($this->ds) ;
//echo $this->ds;
$this->isLdapUser =
$this->LdapUser->isLdapUser($this->username .
//debug($this->isLdapUser);
if ( $this->username =='tsc' || $this->ds ){
if ($this->isLdapUser || 'tsc' ) {
// Get all the user information and store in Session
$this->User->id = $this->Auth->user('id');
$this->User->contain(array('User', 'Role' => array('Ui', 'Action.name')));
$this->Session->write('User', $this->User->read());
$actions = array();
foreach ($this->Session->read('User.Role.Action') as $key => $value){
array_push($actions, $value['name']);
}
$this->Session->write('User.Role.Action', $actions);
// Render different layout depending on user type
if($this->Session->read('User.Role.Ui.name') == Configure::read('usertype.msp')){
$this->Session->write('SessionValues.ui', Configure::read('usertype.msp'));
$this->Auth->loginRedirect = array('controller' => 'PortStats', 'action' =>
'index');
}
else if($this->Session->read('User.Role.Ui.name') ==
Configure::read('usertype.tsc')){
$this->Session->write('SessionValues.ui', Configure::read('usertype.tsc'));
$this->Auth->loginRedirect = array('controller' => 'PortStats', 'action' =>
'index');
}
else if($this->Session->read('User.Role.Ui.name') ==
Configure::read('usertype.superAdminUserType')){
$this->Auth->loginRedirect = array('controller' => 'uis', 'action' => 'index');
}
// Redirect to main login page
$this->redirect($this->Auth->loginRedirect);
}
else {
// Failed login
session_destroy();
$this->Session->setFlash(__('Login failed: access not granted'), 'default',
array(), 'fail');
}
}
else {
// Failed login
session_destroy();
$this->Session->setFlash(__('Login failed: LDAP out of reach'), 'default',
array(), 'fail');
}
}
else {
// Failed login
$this->Session->setFlash(__('Invalid username or password, please try again'),
'default', array(), 'fail');
}
}
}
}
I get:
Warning (2): ldap_bind() [http://php.net/function.ldap-bind]: Unable to bind to
server: Invalid credentials [APP/Model/LdapUser.php, line 56]
Warning (512): Model "User" is not associated with model "User" [CORE/Cake/Model
/Behavior/ContainableBehavior.php, line 339]
My guess is that could be something with case sensitivity between platofrms but it's really bothering that doesn't work in Ubuntu....
[Edited] There is my User model:
<?php
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
public $name = 'User';
var $actsAs = array('Containable');
// Define which database to use
var $useDbConfig = 'myDb';
// Many-To-One relationship
var $belongsTo = array('Role');
// validation of input data
public $validate = array(
'username' => array(
'required' => array(
'rule' => 'notEmpty',
'message' => 'A username is required'
),
'isUnique' => array (
'rule' => 'isUnique',
'message' => 'This username already exists'
)
),
'password' => array (
'not_empty' => array (
'rule' => 'notEmpty',
'message' => 'The field "Password" cannot be empty'
),
'between_chars' => array (
'rule' => array ('between', 4, 10),
'message' => 'Password must be between 4 and 10 chars'
)
),
'passwordVerify' => array(
'not_empty' => array (
'rule' => 'notEmpty',
'message' => 'The field "Confirm Password" cannot be empty'
),
'match_password' => array (
'rule' => 'matchPasswords',
'message' => '"Confirm Password" must be the same as "Password"'
)
),
'name' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A name is required'
)
),
'surname' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A surname is required'
)
),
'role_id' => array(
'valid' => array(
'rule' => 'notEmpty',
'message' => 'Please enter a valid role',
'allowEmpty' => false
)
),
'oldPassword' => array (
'match_password' => array (
'rule' => 'matchOldPassword',
'message' => 'Invalid password'
),
'required' => array (
'rule' => 'requiredOldPassword',
'message' => '"Current Password" is required if you wish to edit the password'
)
),
'newPassword' => array (
'required' => array (
'rule' => 'requiredNewPassword',
'message' => '"New Password" is required if you wish to edit the password'
),
'between_chars' => array (
'rule' => 'lengthNewPassword',
'message' => 'Password must be between 4 and 10 chars'
)
),
'newPasswordVerify' => array (
'required' => array (
'rule' => 'requiredNewPasswordVerify',
'message' => '"Confirm Password" is required if you wish to edit the password'
),
'match_password' => array (
'rule' => 'matchNewPasswordVerify',
'message' => '"Confirm Password" must be the same as "New Password"'
)
)
);
// Verify that password and password verification match when creating a new user
public function matchPasswords ($data) {
if ($this->data['User']['password'] == $this->data['User']['passwordVerify']) {
return true;
} else {
return false;
}
}
public function matchOldPassword ($data) {
if (!empty($this->data['User']['oldPassword'])){ // when an input is given for
'oldPassword'...
if ($_SESSION['User']['User']['password'] ==
AuthComponent::password($this->data['User']['oldPassword'])) { // when password
is correct (equal to 'password')
return true;
} else { // when password is invalid (not equal to 'password')
return false;
}
}
return false; // default value when 'oldPassword' is empty
}
// Verify that a value for 'oldPassword' (current password) is given when
'newPassword' or 'newPasswordVerify' are also given during the procedure of
editing the password
public function requiredOldPassword ($data) {
if (!empty($this->data['User']['newPassword']) || !empty($this->data['User']
['newPasswordVerify'])){ // when an input is given for 'newPassword' or
'newPasswordVerify'...
if (!empty($this->data['User']['oldPassword'])){ // when an input is given for
oldPassword...
return true;
} else { // when no input is given for oldPassword...
return false;
}
}
return false; // default value when 'newPassword' and 'newPasswordVerify'
are left empty
}
// Verify that a value for 'newPassword' (current password) is given when
public function requiredNewPassword ($data) {
if (!empty($this->data['User']['oldPassword']) ||
!empty($this->data['User']['newPasswordVerify'])){ // when an input is given for
'oldPassword' or 'newPasswordVerify'...
if (!empty($this->data['User']['newPassword'])){
return true;
} else { // when no input is given for newPassword...
return false;
}
}
return false;
}
// Verify that 'newPassword' has an appropriate length
public function lengthNewPassword ($data) {
if (!empty($this->data['User']['newPassword'])) { )>=4 && .
strlen($this->data['User']['newPassword'])<=10){ // when length is valid..
return true;
} else { // when length is invalid...
return false;
}
}
return false; // default value when 'newPassword' is left empty
}
public function matchNewPasswordVerify ($data) {
if ($this->data['User']['newPassword'] == $this->data['User']
['newPasswordVerify']) {
return true;
} else {
return false;
}
}
public function requiredNewPasswordVerify ($data) {
if (!empty($this->data['User']['oldPassword']) ||
!empty($this->data['User']['newPassword'])){ // when an input is given for
'oldPassword' or 'newPassword'...
if (!empty($this->data['User']['newPasswordVerify'])){ // when an
return true;
} else { // when no input is given for newPasswordVerify...
return false;
}
}
return false; // default value when 'oldPassword' and 'newPassword' are left empty
}
// Password stored with SHA1 (cakePHP default) or MD5 hashing algorithm
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] =
AuthComponent::password($this->data[$this->alias]['password']);
//$this->data['User']['password'] = md5($this->data['User']
['password']); // MD5 hashing algorithm
}
return true;
}
var $hasMany = array(
'MspDashboard' => array(
'className' => 'MspDashboard',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
[Edit]:
I tend to believe the warning is not responsible for my problem:
It occurs in both platforms but shouldn't interrupt the site's funcionality.
So when in windows in debug level = 2 I see:
But then in ubuntu, it looks buggy all I get is this screen:
About the 512 associated error:
$this->User->contain(array('User', 'Role' => array('Ui', 'Action.name')));
Change to:
$this->User->contain(array('Role' => array('Ui', 'Action.name')));
Don't contain the model itself.
About the LDAP error, seems to be this line:
$this->exists = ldap_bind($this->ds, $user, $pass);
I would start with some code like this to debug:
var_dump($this->ds);
var_dump($user);
var_dump($pass);
$this->exists = ldap_bind($this->ds, $user, $pass);
Copy-paste this data into some LDAP tool and first verify they are correct.
Try this function to get more error information:
http://php.net/manual/en/function.ldap-error.php
OK, mystery solved:
The warning had nothing to do with this:
This line of code is error-proning:
if ($this->isLdapUser || 'tsc' ) {
.......
user tsc is admin in local db and doesn't exist in ldap so is certain to get a time out from ldap_bind, Looks like Ubuntu platform would crash my application on browser timeout. In contrary my local machine will wait during time out time and continue with log-in.
I just modified my code so admin user 'tsc'
will log-in directly without passing from ldap auth.