Conixs
124
7
Laravel

Laravel pagination as load more button

Posted 1 week ago by Conixs

Hello everyone,

I'm trying to use DataTables CDN to display my data without pagination, but with a load more button. Thus, I found out about it on website and tried to implement it as follow:

<script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<script type="text/javascript" src="https://gyrocode.github.io/jquery-datatables-pageLoadMore/1.0.1/js/dataTables.pageLoadMore.min.js"></script>

<script type="text/javascript">
    $(document).ready(function (){
        var table = $('.table-data2').DataTable({
          dom: 'frt',
          ajax: '{{route('users.index')}}',
          drawCallback: function(){
             if($('.au-btn-load').is(':visible')){
                $('html, body').animate({
                   scrollTop: $('.au-btn-load').offset().top
                }, 1000);
             }

             $('.au-btn-load').toggle(this.api().page.hasMore());
          }
        });

        $('.au-btn-load').on('click', function(){
          table.page.loadMore();
        });
    });
</script>

However, it is showing Invalid JSON error. Therefore, I tried to build a resource to send back the data as JSON without success.

class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
        ];
    }
}
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $contributors = Contributor::with('user')->withTrashed()->get();
        return view('users.index', ['contributors' => UserResource::collection($contributors)]);
    }
}

Could someone help me?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.