查询不返回我想要的顺序

时间:2019-05-09 17:01:12

标签: php laravel

这是我的控制者:

$postagens = Postagens::orderBy('created_at','desc')->get();
    return view('index',compact('postagens'));

我的观点:

@foreach ($postagens as $pubs)
@postagens()
        @slot('titulo')
            {{$pubs->nomePost}}
        @endslot

        @slot('descricao')
            {{$pubs->descricao}}
        @endslot

        @slot('nome')
            {{$pubs->usuario}}
        @endslot

        @slot('dia')
            {{$pubs->created_at}}
        @endslot

        @slot('id')
            {{$pubs->id}}
        @endslot        
    @endpostagens
@endforeach

问题是,查询不起作用,我没有得到想要的顺序。仍在返回数据库的顺序。我在做什么错了?

1 个答案:

答案 0 :(得分:-1)

如果您使用compact()帮助器,这会将您的集合(从关系中获取)转换为关联数组,因此无法正常工作

@foreach ($postagens as $pubs)
    {{ $pubs->nomePost }} // <---
@endforeach

尝试以下方法:

@foreach ($postagens as $pubs)
    {{ $pubs['nomePost'] }} // <---
@endforeach

如果要以对象的形式访问属性(箭头符号),则可以使用with()方法传递集合:

$postagens = Postagens::orderBy('created_at','desc')->get();
return view('index')->with('postagens', $postagens);

或建议的版本:

$postagens = Postagens::orderBy('created_at','desc')->get();
return view('index')->withPostagens($postagens);