Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json return in laravel

I have a controller that returns a JSON string as below

$response = Response::json(array("success"=>"true","token"=>$token));

the return value is {"success":"true","token":{}} but when I put a static value like

$response = Response::json(array("success"=>"true","token"=>"12345"));

the return value is correct {"success":"true","token":"12345"}

The variable $token is generated as it is inserted into the database, but not returned properly.

Token is generated from webpatser UUID using: Uuid:generate();

Question: How can I fix that?


UPD:

The var_dump($token) results:

["string":protected]=> string(36) "d0c95650-3269-11e4-a55e-15cdb906eead"

UPD 2:

$response = Response::json(array("success"=>"true","token"=>$token[0]));

returns {"success":"true","token":NULL}

Tried changing the value of $token to other variables such that

$test = "test";

then

$response = Response::json(array("success"=>"true","token"=>$test));

return {"success":"true","token":"test"}

like image 769
sazoo Avatar asked Mar 24 '26 18:03

sazoo


1 Answers

Your $token variable contains an object, that have value as a protected member, which json encoder can not access to.

There probably should be the way to get it with some getter methods, like $token->getValue() or something similar. In such case you need to change your response to

$response = Response::json(array("success"=>"true","token"=>$token->getValue()));

If you could provide the class methods by get_class_methods(), I may be able to suggest further.

As a workaround (it is not actually the preferred way to do this) you may try to use reflection:

<?php
header('Content-Type: text/plain; charset=utf-8');

class A {
    protected $test = 'xxx';

    public function change(){
        $this->test = 'yyy';
    }
}

$a = new A();
$a->change();

$class    = new ReflectionClass(get_class($a));
$property = $class->getProperty('test');

$property->setAccessible(true); // "Dark "magic"

echo $property->getValue($a); // "Dark magic"
?>

Shows:

yyy

So in your code it might be like this:

$class    = new ReflectionClass(get_class($token));
$property = $class->getProperty('string');

$property->setAccessible(true);

$token = $property->getValue($token);

$response = Response::json(array("success"=>"true","token"=>$token));
like image 130
BlitZ Avatar answered Mar 26 '26 07:03

BlitZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!