我用 Laravel 制作了一个简单的表单,但我无法正确返回我的数据。我有一个表格,并将我的数据发送给控制器。在控制器中,我从数据库中检索正确的数据,检索后我将其返回到视图。
但是,我的数据以数组形式返回,其中包含一个对象,我无法找出如何仅获取 p 元素的第一项以及如何在没有 foreach 中的括号的情况下正常显示它。
对于我尝试过的 p 元素:
对于 foreach,我现在知道为什么它显示这些括号了。结果是正确的,但我不知道如何去掉括号。
有人可以帮我解决这个问题吗?
我的html
<form action="store" method="post">
@csrf
<label for="textfield">choose animal:</label>
<input type="text" id="textfield" name="species" required>
<input type="submit" value="Submit">
</form>
@if(isset($data))
<p>result: {{ $data }}:</p>
@foreach($data as $animal){
<ul>
{{$animal->animal}} {{$animal->food}}
</ul>
}
@endforeach
@endif
我的功能
public function store(Request $request)
{
$animal= $request->animal;
$resultAnimal= $this->retrieve($animal);
return view('welcome')->with('data', $resultAnimal);
}
public function retrieve($animal)
{
return DB::table('animals')
->where('species', $animal)
->get();
}
我的路线 路线::post('/store', [Controller::class, 'store']);
看来您拉错了领域。
$animal= $request->animal;
根据您的 HTML 输入,这应该是:
$animal= $request->species;
您还在数据库上使用
->get()
,这将返回一个集合。
get方法返回一个Illuminate\Support\Collection实例 包含查询结果,其中每个结果都是一个实例 PHP stdClass 对象的
如果您想抓取单行,请使用
->first()
您可以阅读有关抓取单行的更多文档,但您也可以这样做
https://laravel.com/docs/10.x/queries#retriving-a-single-row-column-from-a-table
public function store(Request $request)
{
$animal= $request->species;
$resultAnimal= $this->retrieve($animal);
return view('welcome')->with('data', $resultAnimal);
}
public function retrieve($animal)
{
return DB::table('animals')
->where('species', $animal)
->first();
}