Laravel请求 - 检索数据



我需要一些帮助来循环浏览我通过表单提交的数据:

{
"_token": "MYJZs0EIuYMKvD7Y56R8DluxGu9vKJuNkMxXy2Ll",
"name": "Routine 1",
"sections": {
"section-1": {
"section-name": "Section 1",
"exercises": {
"1": {
"name": "Exercise 1"
},
"2": {
"name": "Exercise 2"
}
}
},
"section-2": {
"section-name": "Section 2",
"exercises": {
"3": {
"name": "Exercise 21"
},
"4": {
"name": "Exercise 22"
}
}
}
},
"submit": "Submit"
}

如何正确循环和访问单个值? 我希望它打印出来:

<h2>Section 1</h2><br/>
<p>Exercise 1</p><br/>
<p>Exercise 2</p><br/>
<h2>Section 2</h2><br/>
<p>Exercise 21</p><br/>
<p>Exercise 22</p><br/>

我被困在这里:

public function store(Request $request)
{
$data = $request;
$html = "";
foreach($data as $element){
$html .= "<h2>" . $element->name .'</h2>';
}
return $html;
}

我知道它的存储方法,但在保存其数据之前,我想返回自己的纯 html 以查看是否一切正常,所以忽略它。

我知道

它的存储方法,但在保存它的数据之前,我想向自己返回纯 html 以查看是否一切正常,所以忽略它。

如果你想这样做..为什么要打服务器?您可以向用户显示带有请求数据的模式,然后在确认后继续向服务器发出请求。

PS:我假设你正在使用刀片。

无论如何,忽略这一点,您可以将数据返回到同一视图并在那里循环数据:

public function confirmData(Request $request)
{
$data = $request->all(); // Getting your values (I'll suggest you to use only() instead)
return view('some_view')->with('data', $data);
}

那么在您看来:

@foreach($data as $key => $value)
<span>{{ $value }}</span>
@endforeach

更新

要实现您想要的,请尝试以下操作(我基于您发布的 json(:

public function confirmData(Request $request)
{
$sections = $request->get('sections');
$html = '';
foreach($sections as $section)
{
$html .= "<h2> { $section['section-name'] } </h2>";
foreach($section['exercises'] as $exercise)
{
$html .= "<p> { $exercise['name'] } </p>";
}
}
// ...
return $html;
}

最新更新