gpt4 book ai didi

php - Laravel Blade @foreach 不工作

转载 作者:可可西里 更新时间:2023-11-01 13:54:11 25 4
gpt4 key购买 nike

我正在学习 Laravel 4,到目前为止一切顺利。但是由于某些奇怪的原因,blade 的@foreach 似乎不适用于简单的查询。我的代码是:

路线:

Route::get('/users', function(){

$users = User::all();

return View::make('users/index')->with('users',$users);

});

现在在 index.blade.php 中我的代码是:

  @foreach ($users as $user)

<p>User: {{ $user->username }}</p>

@endforeach

奇怪的是,当我将对象转储到 View 中时,它确实起作用了:

{{ dd($users->toArray())}}

数据库数据以原始数组形式显示。

我不太确定我在这里做错了什么,这几乎是初学者教程中的代码。

最佳答案

你应该使用一个模板/布局(但你没有根据你的view on Github使用)并且 subview 应该扩展它,例如,你的index.blade.php View 应如下所示:

// index.blade.php
@extends('layouts.master')
@section('content')
@foreach ($users as $user)
<p>User: {{ $user->username }}</p>
@endforeach
@stop

现在确保在你的 app/views/layouts 文件夹中你有一个 master.blade.php 布局,它包含如下内容:

// master.blade.php
<!doctype html>
<html class="no-js" lang="">
<head>
<style></style>
</head>
<body>
<div class='content'>
@yield('content') {{-- This will show the rendered view data --}}
</div>
</body>
</html>

dd($users->toArray()) 也可以工作,因为它使用 var_dump 转储 $user->toArray() 和使用die 函数退出脚本,dd 表示dump and die

关于php - Laravel Blade @foreach 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24225344/

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