I have a query in laravel that I want to pass in json. Problem is both the key and value gets passed to the variable I assigned . I tried passing $data= json_encode($ip); inside the controller and return it in the view but I only get one result. How can I get the value only?
Controller
public function displayIP()
{
$ipadd = DB::table('seatplan_client')->select('ipadd')->get();
foreach ($ipadd as $ipadds)
{
$ip = $ipadds->ipadd;
$data= json_encode($ip);//test
echo $data;
}
return View::make('seatplan')->with('ipadd',$ipadd);
}
View
<script> var takenSeats = {{ json_encode($ipadd) }}</script>
Result in Page Source
var takenSeats = [{"ipadd":"192.168.240.1"},{"ipadd":"192.168.240.2"},{"ipadd":"192.168.240.23"},{"ipadd":"192.168.240.38"}]
You need to make an array that "translates" your object:
$ipadsArray = array();
foreach ($ipadd as $ipadds)
{
$ipadsArray[] = $ipadds->ipadd;
}
return View::make('seatplan')->with('ipadd',$ipadsArray);
You need to do this because you are using laravel's ORM which returns stdObjects and when you serialize it you also get the public properties.
If you have a model you could implement serializable interface
<script> var takenSeats = {{ json_decode($ipadd) }}</script>
This will convert your json array to php array. You can omit the keys if you don't want to use it.
Related
One of the routes I'm making for my API in laravel requires me to pass a variable to a ->each() function.
This can be seen below:
public function by_location($zone_id)
{
$zone = Zone::where('id', $zone_id)->get()[0];
error_log($zone->id);
$exhibitors = Exhibitor::where('zone_id', $zone_id)->get();
$exhibitors->each(function($exhibitor, $zone)
{
error_log($zone->id);
$exhibitor['zone_info'] = $zone;
});
return response()->json($exhibitors);
}
This first error_log outputs '2', but with the second I get 'Trying to get property 'id' of non-object'.
Any help is apprecited!
You probably want to use $zone which you selected from database on first line.
Also if you want to change value of item you are iterating you have to use ->map() instead of ->each()
I changed ->get()[0] to ->first(). Never use ->get()[0]
public function by_location($zone_id)
{
$zone = Zone::where('id', $zone_id)->first();
error_log($zone->id);
$exhibitors = Exhibitor::where('zone_id', $zone_id)->get();
$exhibitors->map(function($exhibitor) use ($zone){
error_log($zone->id);
$exhibitor['zone_info'] = $zone;
return $exhibitor;
});
return response()->json($exhibitors);
}
I'm working on magento site and facing strange error when array values assign inside function and retrieve outside of function.
//define array
$ctall=array();
//function for array value assign
function printtest($fg){
//global variable
global $ctall;
//just assign to array
$ctall[rand(10000,100000)]=$fg;
//this var dump shows array with vaues when function calling
// var_dump($ctall);
}
i call the function here inside an another function
$categoryTree = Mage::getResourceModel('catalog/category')->getCategories($categoryId, 0, true);
$printCategories = function($nodes) use (&$printCategories) {
foreach ($nodes as $_category):
$ctdf=$_category->getId();
$categoryn = Mage::getModel('catalog/category')->load($ctdf);
if($ctdf!='' && $categoryn->getIsActive()):
//here call to function by passing a value
printtest($ctdf);
$printCategories($_category->getChildren());
endif;
endforeach;
};
$printCategories($categoryTree);
//sleep(10);
// i try to get array results here but it shows empty
var_dump($ctall);
Anyone know how to fix this, i tried hours without luck. Thank You
remove all declaration of $ctall, and try this:
//remove define array, don't define it
// $ctall=array();
function printtest($fg){
if(!isset($GLOBALS['ctall'])){
$GLOBALS['ctall'] = array();
}
//assign to global
$GLOBALS['ctall'][rand(10000,100000)]=$fg;
}
on outside, dump like this:
var_dump($GLOBALS['ctall'])
Try to push instead of assigning.Try this:
$ctall[][rand(10000,100000)]=$fg; //notice the empty square brackets
you can try this also:
function printtest($fg){
global $ctall;
$new_array =array();
$new_array[rand(10000,100000)] = $fg;
array_merge($ctall, $new_array);
}
I am getting the error;
No query results for model [App\UserProfile] 0
When I use findOrFail using an array passed with AJAX in a foreach loop. If I manually create the array in PHP, the entity is found using the array values. When I do a print_r() on the array in PHP, the array is present in both the AJAX array and the manually created array.
AJAX Code
function checkChatOnlineStatus()
{
var chatUserProfileIds = {"key-60":60,"key-52":52,"key-2":2,"key-3":3}
$.ajax({
url: '/check-chat-online-status',
method: 'get',
data: {chatUserProfileIds: chatUserProfileIds},
dataType: 'json',
success: function(response) {
}
});
}
PHP Code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\UserProfile;
class CheckRunningParametersController extends Controller
{
public function checkChatOnlineStatus()
{
$chatUserProfileIds = $_GET['chatUserProfileIds'] ? $_GET['chatUserProfileIds'] : NULL;
//$chatUserProfileIds = array('key-60' => 60, 'key-52' => 52, 'key-2' => 2, 'key-3' => 3);
/* Check Status For Chat Contacts */
if ($chatUserProfileIds != NULL)
{
foreach ($chatUserProfileIds as $key => $value)
{
$userProfile = UserProfile::findOrFail((int)$value);
$chatOnlineStatus['contacts'][$key] = $userProfile->isOnline();
}
}
return $chatOnlineStatus;
}
}
Here Your PHP code will be like this
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\UserProfile;
class CheckRunningParametersController extends Controller
{
public function checkChatOnlineStatus()
{
$chatUserProfileIds = $_GET['chatUserProfileIds'];
/* Check Status For Chat Contacts */
if ($chatUserProfileIds != NULL)
{
foreach ($chatUserProfileIds as $key => $value)
{
$userProfile = UserProfile::where("id",(int)$value)->first();
$chatOnlineStatus['contacts'][$key] = $userProfile->isOnline();
}
}
return $chatOnlineStatus;
}
}
Try this simple code
if( $chatUserProfileIds ){
$userProfile = UserProfile::whereIn("id",array_values($chatUserProfileIds))->get();
}
and iterate over result and populate online status etc and return result.
Using findOrFail() will throw an exception if there is no UserProfile with that id. It is possible that you are pushing id numbers back to Laravel's DB that don't exist. If you don't want the exception and wish to self check, use first() or find() and then do an if check for isset to see if a model was returned, or a null value if the ID doesn't match a UserProfile. IE:
$userProfile = UserProfile::find((int)$value);
if(isset($userProfile)
$chatOnlineStatus['contacts'][$key] = $userProfile->isOnline();
If you are sure the UserProfile is present with the IDs you are passing, it may be an issue with a string being cast to an int the wrong way. Check to see exactly what (int) is being passed via a dd(). You may also wish to use the native Laravel \Input::get('chatUserProfileIds') instead of $_GET.
#Muhammad Sadiq
I have tried;
if( $chatUserProfileIds != NULL ){
$userProfiles = UserProfile::whereIn("id",array_values($chatUserProfileIds))->get();
foreach ($userProfiles as $userProfile)
{
//print_r($userProfile->id);
$chatOnlineStatus['contacts'][$userProfile->id] = $userProfile->isOnline();
}
}
The code only works if I remove the comments on print_r statement or add any other statement like echo at that point
I found the problem. Silly mistake really. I moved the assignment of data to the JavaScript object used in the array to the global scope and that seems to work.
// Moved this to global scope in the Javascript
var chatUserProfileIds = {"key-60":60,"key-52":52,"key-2":2,"key-3":3}
Edit
Thanks for all the input on this, I did find error in my question so modifying now. Sorry for that.
I am trying to figure out how to return the last object in the JSON string I have rendered. The two functions I am working with:
public function revision($return = false)
{
$id = $this->input->post('galleryID');
$data = array('revision_count' => $this->revision->count_revision($id) );
if($return){
return json_encode($data);
}
else {
echo json_encode($data);
}
}
public function last_revision()
{
$allRevisions = json_decode($this->revision(),true);
return end($allRevisions);
}
The issue is that end() returns error stating that 1st parameter should be array.
Thanks for any help on this.
It is important to note here that json_decode returns an instance of stdClass by default. Try using json_decode($jsonstring, true) to return the JSON as a PHP associative array.
However, You haven't included what the $this->revision() method does. Could you possibly show that portion of the code, since that is the function you are getting a return value from?
Edit:
Alright, after we saw the right function in your code, here are a couple of things I would like to say:
You have added a $return parameter to your revision method, but you aren't using it when you need to. You should change $this->revision() to $this->revision(true) in your last_revision method.
If you're going to return data from the revision() method, there's not much of a point in json_encodeing it, just to json_decode the result. Just pass back the raw data array.
Once you have changed both of these things, this should work:
$allRevisions = $this->revision(true); return end($allRevisions['revision_count']);
You can change the edit_function() to:
public function edit_revision($return = false)
{
$galleryID = $this->input->post('galleryID');
$revisionID = $this->input->post('revisionID');
$data = array('revision_images' => $this->revision->get($galleryID, $revisionID) );
if($return)
return json_encode($data);
else
echo json_encode($data);
}
and then:
public function last_revision(true)
{
$allRevisions = json_decode($this->revision());
return end($allRevisions);
}
Maybe you need convert that json output to an php array (json_decode() function), then you could get the last item with array_pop() function:
https://php.net/array_pop
I am building a Language class for internationalization, and I would like to access the properties dynamically (giving the string name), but I don't know how to do it when dealing with arrays (this is just an example):
class Language {
public static $languages_cache = array();
public $index_header_title;
public $index = array(
"header" => array(
"title" => NULL
)
);
}
Now I add languages like this:
Language::$languages_cache["en"] = new Language();
Language::$languages_cache["en"]->index_header_title = "Welcome!"; //setting variable
Language::$languages_cache["en"]->index["header"]["title"] = "Welcome!"; //setting array
Function for accessing members dynamically:
function _($member, $lang)
{
if (!property_exists('Language', $member))
return "";
return Language::$languages_cache[$lang]->$member;
}
So, outputting members:
echo _('index_header_title', "en"); //works
echo _('index["header"]["title"]', "en"); //does not work
I would need a way for accessing arrays dynamically.. for public and private via __set() function.
Thank you!
You could try using a separator flag so that you can parse the array path. The only problem is you are mixing you properties and arrays so that might complicate things.
You would call your function like this:
echo _('index.header.title', "en");
And your function would parse the path and return the correct value. Take a look at the array helper in Kohana 3.0. It has the exact function that you want. http://kohanaframework.org/guide/api/Arr#path