Laravel Blade @foreach not working

旧城冷巷雨未停 提交于 2019-12-10 14:53:24

问题


I'm learning Laravel 4, so far so good. But for some weird reason blade's @foreach doesn't seem to work for a simple query. My code is:

Route:

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

    $users = User::all();

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

});

Now in index.blade.php my code is:

  @foreach ($users as $user)

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

  @endforeach

The weird thing is that when I dump the object in the view, it does work:

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

The DB data is displayed raw as an array.

I'm not really sure what am I doing wrong here, this is pretty much code from the beginners tutorial.


回答1:


You should use a template/layout (but you didn't use according to your view on Github) and child views should extend it, for example, your index.blade.php view should be look something like this:

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

Now make sure that, in your app/views/layouts folder you have a master.blade.php layout and it contains something like this:

// 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>

Also dd($users->toArray()) works because it dumps the $user->toArray() using var_dump and exits the script using die function, the dd means dump and die.



来源:https://stackoverflow.com/questions/24225344/laravel-blade-foreach-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!