2016-07-17 66 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