2016-07-17 71 views
0

我想从我的角度应用程序的请求访问对象属性对象属性。我使用Laravel 5.1无法从网址参数访问Laravel

角:

console.log('getQuestionAnswers', params); 
return $http({ 
    method: 'GET', 
    url: url + ver + '/questions/checkMany', 
    params: { 
     'questions[]' : params 
    }, 
    headers: { 
     'Content-Type': 'application/json', 
     Authorization: 'Bearer ' + $rootScope.access_token 
    }, 
    cache: true 
}); 

CONSOLE.LOG则params的:

enter image description here

Laravel:

public function getAnswers(Request $request) 
{ 
    $input = $request->all(); 

    $question_objs = $input['questions']; 

    foreach ($question_objs as $question_answer_object) { 
     return $question_answer_object; 

响应角度与:return $question_objs;

enter image description here

响应角度与:return $question_answer_object;

enter image description here

看起来越远越好!


但是,如果我尝试laravel内访问属性,像question_id:

return $question_answer_object['question_id'];

我得到错误:

"Illegal string offset 'question_id'

Laravel已经解析JSON,

// From Illuminate/Http/Request.php all() method: 

    if (! isset($this->json)) { 
     $this->json = new ParameterBag((array) json_decode($this->getContent(), true)); 
    } 

当我返回时,我可以看到它是一个对象。为什么我无法访问这些属性?我也试过json_decode没有运气。


使用JSON解码:

$test = json_decode($question_answer_object, true); 
return $test['question_id']; 

这似乎是工作。但为什么?


访问对象的属性这样:

return $question_answer_object->question_id; 

提供了以下错误:

"Trying to get property of non-object"

+0

@ChoncholMahmud plz见上面的尝试与json解码 – Growler

+0

@ChoncholMahmud没关系,它的工作。但我认为Laravel的$ request-> all()会返回array_replace_recursive($ this-> input(),$ this-> files-> all());'和递归的'json_decodes'?你可以解释吗? – Growler

回答

1

$question_answer_object['question_id']的变量是包括JSON编码数据的字符串来存取权限它;访问,你需要首先解码:

$decoded= json_decode($question_answer_object['question_id'], true); 
return $decoded['question_id']; 

如果你不发送请求的应用程序/ JSON,使用$request->json()。 你可以得到关于这个问题的一些信息here

0

返回问题是一个对象,而不是阵列。你有->

return $question_answer_object->question_id; 
+0

我无法使用'obj ['key']'访问对象的属性? – Growler

+0

除非对象实现了由'json_decode'返回的'stdClass'没有的'ArrayAccess'接口。 – Finwe

+0

请参阅上面的编辑。我试图获得非对象的属性'' – Growler