Array to string conversion Error in Laravel 4.2 - php

I was working in one Laravel Project using 92Five App. when access user List. its goto Something Went Wrong Page. Its Display Array to string conversion Error in Error Log.
In User Controller Following Functions are Defined.
Error :
[2016-08-09 13:13:12] log.ERROR: Something Went Wrong in User
Repository - getAllUsersData():Array to string conversion [] []
My Code :
public function getAllUsersData()
{
try{
$users = array();
$tempUsers = \User::all()->toArray();
$users = $this->getGroupBaseRole($tempUsers);
return $users;
}
catch (\Exception $e)
{
\Log::error('Something Went Wrong in User Repository - getAllUsersData():'. $e->getMessage());
throw new SomeThingWentWrongException();
}
}
public function getGroupBaseRole($groupMembersInfo) {
$data = [];
if(!empty($groupMembersInfo) && isset($groupMembersInfo)) {
foreach($groupMembersInfo as $user)
{
$banned = false;
$suspended = false;
$loginAttempt = 0;
$usersThrottle = \Throttle::where('user_id',$user['id'])->get()->toArray();
// print_r($usersThrottle); exit;
if(sizeof($usersThrottle) != 0)
{
foreach($usersThrottle as $userThrottle)
{
if($userThrottle['banned'] == true)
{
$banned = true;
}
if($userThrottle['suspended'] == true)
{
$suspended = true;
}
$loginAttempt = $loginAttempt + $userThrottle['attempts'];
}
$user['banned'] = $banned;
$user['suspended'] = $suspended;
$user['loginAttempt'] = $loginAttempt;
}
else
{
$user['banned'] = false;
$user['suspended'] = false;
$user['loginAttempt'] = 0;
}
$groupUser = \Sentry::findUserById($user['id']);
$groups = $groupUser->getGroups()->toArray();
if(sizeof($groups)!=0)
{
$user['role'] =$groups[0]['name'];
}
else
{
$user['role'] = '';
}
$data[] = $user;
}
}
return $data;
}

It seeems getGroupBaseRole() method accepts string, but you're trying to pass an array $tempUsers as first argument.

Related

How to update or insert new data on codeigniter

I'm setting up a rest-API on my server, and I want to update a table (i.e "comp_holding_stock"). but every time I test to post new data it returns "No item found"
Here is my controller
public function create_comp_holding_stock(){
$returnArr['status'] = '0';
$returnArr['response'] = '';
try {
if (!$this->input->post()) {
$returnArr['response'] = "Only POST method is allowed";
} else {
$holding_stock_data = array(
'comp_id' => $this->input->post('comp_id'),
'customer_id' => $this->input->post('customer_id'),
'quantity' => $this->input->post('quantity'),
'date' => date('Y-m-d H:i:s')
);
if (!isset($holding_stock_data)) {
$returnArr['response'] = "Some Parameters are missing";
} else {
$customer = $this->Customer->save_holding_stock($holding_stock_data);
if (!$customer) {
$returnArr['response'] = 'No items found';
} else {
$returnArr['status'] = '1';
$returnArr['response'] = $customer;
}
}
}
} catch (Exception $ex) {
$returnArr['response'] = "Error in connection";
$returnArr['error'] = $ex->getMessage();
}
$response = json_encode($returnArr, JSON_PRETTY_PRINT);
echo $response;
}
And here is my model below
public function save_holding_stock($holding_stock_data)
{
// $this->db->trans_start();
$success = $this->db->insert('comp_holding_stock', $holding_stock_data);
return $success;;
}
what am i doing wrong? what is the best approach to this scenarios
I would recommend try to check if you have load model in your controller.
And in your model try to do this.
public function save_holding_stock($holding_stock_data, $comp_id=FALSE)
{
if(!$comp_id == -1 || !$this->exists($comp_id))
{
if($this->db->insert('comp_holding_stock', $holding_stock_data))
{
$holding_stock_data['comp_id'] = $this->db->insert_id();
return TRUE;
}
return FALSE;
}
$this->db->where('comp_id', $comp_id);
return $this->db->update('comp_holding_stock', $holding_stock_data);
}
Try these changes in your code
In your controller,
$customer = $this->Customer->save_holding_stock($holding_stock_data);
$save_status = $this->db->affected_rows();
if ($save_status>0) {
$returnArr['status'] = '1';
$returnArr['response'] = $customer;
} else {
$returnArr['response'] = 'No items found';
}
In your model,
public function save_holding_stock($holding_stock_data)
{
// $this->db->trans_start();
$this->db->insert('comp_holding_stock', $holding_stock_data);
}

Use PHP function to override default JSON target with Array

We built an API to directly access other social networks APIs using our keys.
I'm trying to build a fuction to access that API.
The default function has been written and is working.
Question
How can I specify a new array to target the json data?
This will override the default setting.
function SocialAPI($handle, $service, $path="") {
$handle = strtolower($handle);
$service = strtolower($service);
$api = file_get_contents("https://api.service.domain.com/v1/Social?handle=$handle&service=$service");
if($api !== false) {
$data = json_decode($api, true);
if($data !== null) {
if($service === "twitter") {
return $data['0']['followers_count'];
}
if($service === "instagram") {
if(!empty($path)) {
while($id = array_shift($path)) {
echo $data[$id];
}
return $data;
} else {
return $data['user']['followed_by']['count'];
}
}
} else {
return false;
}
} else {
return "API call failed.";
}
}
//Test API Function - ** TO BE DELETED **
echo SocialAPI("JohnDoe", "Instagram", "['user']['full_name']");
exit();
function array_deref($data, $keys) {
return empty($keys) ? $data
: array_deref($data[$keys[0]], array_slice($data, 1))
}
function SocialAPI($handle, $service, $path="") {
$handle = strtolower($handle);
$service = strtolower($service);
$api = file_get_contents("https://api.service.domain.com/v1/Social?handle=$handle&service=$service");
if ($api === false) {
return "API call failed.";
}
$data = json_decode($api, true);
if($data !== null) {
return false;
}
if ($service === "twitter") {
if (empty($path)) $path = ['0','followers_count'];
return array_deref($data, $path);
} elseif ($service === "instagram") {
if (empty($path)) $path = ['user','followed_by'];
return array_deref($data, $path);
}
}
//Test API Function - ** TO BE DELETED **
echo SocialAPI("JohnDoe", "Instagram", ['user', 'full_name']);
echo SocialAPI("JohnDoe", "Instagram");
exit();
I added a utility function, array_deref, to walk the arrays recursively (calls itself to handle each level down).

PHP get link from txtfile, unset this link inside the array and get random array value

I'm trying to load a website url from a textfile, then unset this string from an array and pick a random website from the array.
But once I try to access the array from my function the array would return NULL, does someone know where my mistake is located at?
My current code looks like the following:
<?php
$activeFile = 'activeSite.txt';
$sites = array(
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
);
function getActiveSite($file)
{
$activeSite = file_get_contents($file, true);
return $activeSite;
}
function unsetActiveSite($activeSite)
{
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}
function updateActiveSite($activeFile)
{
$activeWebsite = getActiveSite($activeFile);
if(!empty($activeWebsite))
{
$unsetActive = unsetActiveSite($activeWebsite);
if($unsetActive == true)
{
$randomSite = $sites[array_rand($sites)];
return $randomSite;
}
else
{
echo 'Could not unset the active website.';
}
}
else
{
echo $activeWebsite . ' did not contain any active website.';
}
}
$result = updateActiveSite($activeFile);
echo $result;
?>
$sites is not avaliable in unsetActiveSite function you need to create a function called "getSites" which return the $sites array and use it in unsetActiveSite
function getSites(){
$sites = [
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
];
return $sites;
}
function unsetActiveSite($activeSite)
{
$sites = getSites();
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}

Magento Get Category URL in Index Controller

I am having troubles getting my redirectURL to grab the current URL inside of my IndexController. I have written something very similar that grabs the current product URL, but this is for the category. Can someone explain what I may have done wrong?
<?php
class Magestore_Categoryinquiry_IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
$this->_initLayoutMessages('catalog/session');
$this->loadLayout();
$this->renderLayout();
}
public function submitAction() {
$data = $this->getRequest()->getPost();
$error = false;
if($data) {
$category = Mage::getModel('catalog/category')->load($data['category_id']);
try {
$postObject = new Varien_Object();
$postObject->setData($data);
$error = false;
if (Mage::helper('categoryinquiry')->isRequireFname()) {
if (!Zend_Validate::is(trim($data['fname']) , 'NotEmpty')) {
$error = true;
}
}
if (Mage::helper('categoryinquiry')->isRequireLname()) {
if (!Zend_Validate::is(trim($data['lname']) , 'NotEmpty')) {
$error = true;
}
}
if (Mage::helper('categoryinquiry')->isRequireEmail()) {
if (!Zend_Validate::is(trim($data['customer_email']), 'EmailAddress')) {
$error = true;
}
}
if (Zend_Validate::is(trim($data['hideit']), 'NotEmpty')) {
$error = true;
}
if ($error) {
throw new Exception();
}
$model = Mage::getModel('categoryinquiry/categoryinquiry');
$data['store_id'] = Mage::app()->getStore()->getId();
$data['status'] = 1;
$data['created_time'] = now();
$data['updated_time'] = now();
$data['category_name'] = $category->getName();
$categoryinquiry = $this->getLayout()->createBlock('categoryinquiry/sendtocustomer')
->setInformation($data)
->setTemplate('categoryinquiry/email/sendtocustomer.phtml')
->toHtml();
$customercontact = $this->getLayout()->createBlock('categoryinquiry/sendtoadmin')
->setInformation($data)
->setTemplate('categoryinquiry/email/sendtoadmin.phtml')
->toHtml();
$model->setData($data)->save()
->sendMailToCustomer($model, $categoryinquiry)
->sendMailToAdmin($model, $customercontact)
;
Mage::getSingleton('catalog/session')->addSuccess(Mage::helper('categoryinquiry')->getSuccessMessage());
$this->_redirectUrl($category->getCategoryUrl());
return;
} catch (Exception $e) {
Mage::getSingleton('catalog/session')->addError(Mage::helper('categoryinquiry')->getErrorMessage());
$this->_redirectUrl($category->getCategoryUrl());
return;
}
}
}
}

How to use eager loading here, i mean just by using one variable instead of two. So i don't need to run two separate queries

1) How can use eager loading here, i mean just by using $SponceringUser instead of $ProfileUser. so i don't need to run two separate queries.
if i exchange my $profileUser variable with $SponceringUser where in the code i should save it to get the right output
here is the Post_edit method for more details please refer gist here : https://gist.github.com/gupta2205/b33dcf762876e5df34d9
public function post_edit($id = null)
{
if ($id)
{
$Petition = Petition::find($id);
if (!$Petition)
{
//oh noes! invalid petition specified!
Alert::error("That petition no longer exists");
return Redirect::action('AdminPetitionsController#index');
}
}
else
{
$Petition = new Petition;
}
$PetitionCreationForm = new AdminPetitionCreationForm;
$errors = array();
if ($PetitionCreationForm->passes())
{
$Petition->call_to_action = Input::get('call_to_action');
if (empty($Petition->id))
{
$Petition->slug = Str::slug($Petition->call_to_action);
}
$Petition->recipient = Input::get('recipient');
if (Input::get('feature_type') == '1')
{
$Petition->featured_sort_order = Input::get('featured_sort_order') + 1;
$Petition->flag_featured = 1;
}
else if(Input::get('feature_type') == '0')
{
$Petition->featured_sort_order=null;
$Petition->flag_featured = 0;
}
//$selected_position = Input::get('dropdown_menu_list');
$Petition->description_md = Input::get('description_md');
$Petition->description = Petition::parseMD($Petition->description_md);
$Petition->letter_md = Input::get('letter_md');
$Petition->letter = Petition::parseMD($Petition->letter_md);
$Petition->target_signatures = Input::get('target_signatures', 50000);
$Petition->flag_published = Input::get('flag_published');
$Petition->media_type = Input::get('media_type', null);
if (Input::get('media_type') == 'img' && Input::hasFile('petition_image'))
{
$Petition->media_url = Petition::uploadFile(Input::file('petition_image'));
}
else if (Input::get('media_type') == 'youtube' && Input::get('media_url_youtube'))
{
$Petition->media_url = Input::get('media_url_youtube');
}
// how to fix this part .... gurrrrrrrrrrrr=======================
$ProfileUser= $Petition->User;
if (Input::get('profile_type') == 'image' && Input::hasFile('profile_image'))
{
$ProfileUser->profile_img_url = Petition::uploadFile(Input::file('profile_image'));
}
else if (Input::get('profile_type') == 'url' && Input::get('profile_url'))
{
$ProfileUser->profile_img_url = Input::get('profile_url');
}
//$Petition->sponsor_user_id = $SponsoringUser->id;
$ProfileUser->save();
//====================================================
try {
try {
$SponsoringUser = User::where('email', Input::get('user.email'))->firstOrFail();
}
catch (Exception $e)
{
$PetitionSponsorForm = new AdminPetitionSponsorForm(Input::get('user'));
if ($PetitionSponsorForm->passes())
{
$SponsoringUser = new User;
$SponsoringUser->email = Input::get('user.email');
$SponsoringUser->first_name = Input::get('user.first_name');
$SponsoringUser->last_name = Input::get('user.last_name');
$SponsoringUser->populateLocation(Input::get('user.zip'));
$SponsoringUser->save();
}
else
{
throw new Exception();
}
}
$Petition->save();
1) How can use eager loading here, i mean just by using $SponceringUser instead of $ProfileUser. so i don't need to run two separate queries.
i got it :)
if (Input::get('profile_type') == 'image' && Input::hasFile('profile_image'))
{
$SponsoringUser->profile_img_url = Petition::uploadFile(Input::file('profile_image'));
}
else if (Input::get('profile_type') == 'url' && Input::get('profile_url'))
{
$$SponsoringUser->profile_img_url = Input::get('profile_url');
}
$SponsoringUser->save();

Categories