gpt4 book ai didi

mysql - Laravel:无法将数据库中的数组从路由器传递到 View

转载 作者:行者123 更新时间:2023-11-29 00:18:11 26 4
gpt4 key购买 nike

我刚开始使用 Laravel,当我尝试从数据库中检索值并尝试通过路由器将它们输出到 View 时卡住了。这是我在路由器中的代码:

Route::get('/', function(){
$posts = DB::select("select title from posts");
return View::make("hello", $posts);
});

使用 Blade 模板查看代码:

@extends('master')

@section('title')
@foreach ($posts as $post) {
{{ $post->title }}
@endforeach
@endsection

我尝试检查查询,它运行完美,但在查看的页面上出现 undefined variable 错误。

enter image description here

我做错了什么,我该如何改正?请帮助..

最佳答案

试试这个:

$posts = DB::select(DB::raw('SELECT title FROM posts'));

或:

$posts = DB::table('posts')->select('title')->get();

并返回 View :

return View::make('hello', ['posts' => $posts]);

在发送到 View 之前,您需要将 $posts 分配给一个变量。在上面,变量是 posts

关于mysql - Laravel:无法将数据库中的数组从路由器传递到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22114400/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com