Laravel 5 如何对文件列表使用分页?

Laravel 5 how to use pagination with files list?

我的脚本有一个问题。我用文件列表做了 foreach 但我需要分页,例如每个站点 15 个文件。我现在应该怎么做?感谢您的帮助:)

控制器:

$files = Storage::allFiles('/upload_file');

return view('cms.viewSystem.gallery.manageFiles')->with('files', $files);

Blade 视图:

<table class="table table-bordered table-striped datatable" id="table-2">
    <thead>
        <tr>
            <th>Nazwa pliku</th>
            <th>Akcje</th>
        </tr>
    </thead>
    <tbody>
    @foreach($files as $file)
        <tr>
            <td>{{ $file }}</td>
            <td>
                <a href="{{ url('cms/media/deleteFile/'.$file) }}" class="btn btn-red btn-sm btn-icon icon-left"><i class="entypo-cancel"></i>Usuń</a>
            </td>
        </tr>
    @endforeach
    </tbody>
</table>

我试过使用 paginate() 但这个选项不起作用:(

Storage::allFiles()函数只是returns一个数组,所以你可以使用内置laravel分页类。请参阅有关分页的文档 https://laravel.com/docs/5.2/pagination

$paginator = new \Illuminate\Pagination\LengthAwarePaginator($items, $total, $perPage);

return view('my.view', ['files' => $paginator]);

在您看来,您随后会正常循环结果,但也可以访问 render() 功能来显示分页链接。

@foreach($files as $file)
    {{ $file }}
@endforeach

{!! $files->render() !!}

您可以做的是:

$page = (int) $request->input('page') ?: 1;

$files = collect(Storage::allFiles('/upload_file'));
$onPage = 15;

$slice = $files->slice(($page-1)* $onPage, $onPage);

$paginator = new \Illuminate\Pagination\LengthAwarePaginator($slice, $files->count(), $onPage);
return view('cms.viewSystem.gallery.manageFiles')->with('files', $paginator);

为了在视图中显示,您可以使用 https://laravel.com/docs/5.1/pagination#displaying-results-in-a-view