3

I have one problem with my script. I did foreach with files list but I need pagination, for example 15 files per site. What should I do now? Thanks for help :)

Controller:

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

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

Blade view:

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

I tried use paginate() but this option not working :(

BassMHL
  • 8,523
  • 9
  • 50
  • 67
Stanisław Szewczyk
  • 105
  • 1
  • 3
  • 11
  • You can create your own `Paginator` instance and pass it the required parameters for pagination (it's mentioned in the [Laravel Documentation](https://laravel.com/docs/5.2/pagination#manually-creating-a-paginator), but there are no examples there. For an example you can have a look at [this answer](http://stackoverflow.com/a/27546775/351330). – Bogdan Jan 03 '16 at 20:43
  • You can use Paginator - look at this question - http://stackoverflow.com/questions/27213453/laravel-5-manual-pagination/27546775#27546775 – Marcin Nabiałek Jan 03 '16 at 20:49

2 Answers2

4

What you can do is:

$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);

And for displaying in view you can use https://laravel.com/docs/5.1/pagination#displaying-results-in-a-view

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
1

The Storage::allFiles() function simply returns an array, so you can use the build in laravel pagination classes. See the docs on pagination https://laravel.com/docs/5.2/pagination

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

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

In your view you then loop over the results as normal, but also have access to the render() function to display pagination links.

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

{!! $files->render() !!}
Wader
  • 9,427
  • 1
  • 34
  • 38