sazoo
sazoo

Reputation: 127

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"}

Upvotes: 3

Views: 2292

Answers (3)

Ahesanali Suthar
Ahesanali Suthar

Reputation: 341

User foreach for $token and get the value from it. Assign it in some variable and use it in your response.

exa.

$my_tocken = "";
foreach ($tocken as $real_tocken){
  $my_tocken = $real_tocken;
}

Now build your response as you usually build with your test variables.

Upvotes: 0

BlitZ
BlitZ

Reputation: 12168

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));

Upvotes: 2

Komal
Komal

Reputation: 2736

You need to provide that via a getter method in the class itself.

So in the class:

public function getData()
{
  return $this->string;
}

And in your program:

$token->getData();

Upvotes: 0

Related Questions