【问题标题】:Unable to access object properties from URL params in Laravel无法从 Laravel 中的 URL 参数访问对象属性
【发布时间】:2016-11-19 23:38:27
【问题描述】:

我正在尝试从我的 Angular 应用程序的请求中访问对象属性。我正在使用 Laravel 5.1

角度:

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

参数的控制台.log:

Laravel:

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

    $question_objs = $input['questions'];

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

回复 Angular:return $question_objs;

回复 Angular:return $question_answer_object;

看起来到目前为止一切都很好!


但如果我尝试访问 laravel 中的属性,例如 question_id:

return $question_answer_object['question_id'];

我得到错误:

"非法字符串偏移'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;

给出以下错误:

"试图获取非对象的属性"

【问题讨论】:

  • @ChoncholMahmud 请参阅上面的 json 解码尝试
  • @ChoncholMahmud 好的,它起作用了。但我认为 Laravel 的 $request->all()return array_replace_recursive($this->input(), $this->files->all()); 和递归 json_decodes?你能解释一下吗?

标签: php angularjs json laravel laravel-5.1


【解决方案1】:

$question_answer_object['question_id'] 变量是一个包含 JSON 编码数据的字符串;要访问它,您需要先对其进行解码:

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

如果您不以 application/json 格式发送请求,请使用 $request->json()。 您可以获取有关此问题的一些信息here

【讨论】:

    【解决方案2】:

    返回的问题是一个对象,而不是一个数组。您必须使用-> 访问它

    return $question_answer_object->question_id;
    

    【讨论】:

    • 我无法使用obj['key']访问对象的属性?
    • 除非对象实现了ArrayAccess 接口,而json_decode 返回的stdClass 没有。
    • 请参阅上面的编辑。我得到"Trying to get property of non-object"
    • 如果是这样的话,为什么会这样:$question_objs = $input['questions']; As $input[questions] is a key
    猜你喜欢
    • 1970-01-01
    • 2021-11-06
    • 2014-03-10
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    相关资源
    最近更新 更多