Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

fishscale's avatar

Help with some coding laravel

I have created a website my first time with laravel well not coded by myself but i do understand a little bit when looking around in files and have edited some stuff myself. But there is one part i have been stuck on for days.

So to my question there is a specific page where my services is listed, they are around 5000 services and when loading that page it is very slow because of so many services loading in one page.

I have been trying to fix three things adding a filter button, search bar and make so the page is paginated where all services is not shown on one page. But here is the thing i have seen other websites load more than 5000 services in one page, what is it i need to do to make the website handle this?

If someone can help me code in the search bar and filter button let me know so i can upload the code.

Thanks

I tried adding search bar, filter button and fixing the slow loading of that specific page but no luck.

Here is the code for that specific page

@extends($activeTemplate . 'layouts.app') @section('panel')

<div class="row gy-4">
    @forelse($categories as $category)
        <div class="col-lg-12">
            <div class="d-flex flex-wrap justify-content-between mb-3 gap-2">
                <h3>{{ __($category->name) }}</h3>

                <a href=''user.service.category', $category->id) }}" class="btn btn-sm btn-outline--primary"> <i
                        class=" las la-list-ul"></i>
                    @lang('View All')</a>
            </div>
            <div class="card b-radius--10">
                <div class="card-body p-0">
                    <div class="table-responsive--lg table-responsive">
                        <table class="table table--light tabstyle--two">
                            <thead>
                                <tr>
                                    <th>@lang('Service ID')</th>
                                    <th>@lang('Service')</th>
                                    <th>@lang('Price Per 1k')</th>
                                    <th>@lang('Min')</th>
                                    <th>@lang('Max')</th>
                                    <th>@lang('Make Order')</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($category->services ?? [] as $service)
                                    <tr>
                                        <td>{{ $service->id }}</td>
                                        <td class="break_line">{{ __($service->name) }} <span class="favoriteBtn @if(in_array($service->id, $myFavorites)) active @endif" data-id="{{ $service->id }}"><i class="la la-star"></i></span>
                                        </td>
                                        <td>
                                            {{ $general->cur_sym . showAmount($service->price_per_k) }}</td>
                                        <td>{{ $service->min }}</td>
                                        <td>{{ $service->max }}</td>

                                        <td>
                                            <button type="button" class="btn btn-sm btn-outline--info detailsBtn"
                                                data-details="{{ $service->details }}" @disabled(!$service->details)> <i
                                                    class="la la-desktop"></i> @lang('Details')
                                            </button>

                                            <button type="button" class=" btn btn-sm btn-outline--primary orderBtn"
                                                data-url="{{ route('user.order.create', $service->id) }}"
                                                data-api_provider_id="{{ $service->api_provider_id }}"
                                                data-price_per_k="{{ getAmount($service->price_per_k) }}"
                                                data-min="{{ $service->min }}" data-max="{{ $service->max }}">
                                                <i class="las la-cart-plus"></i> @lang('Order')
                                            </button>
                                        </td>
                                    </tr>
                                @endforeach

                            </tbody>
                        </table><!-- table end -->
                    </div>
                </div>
            </div><!-- card end -->
        </div>
    @empty
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <h4>
                        {{ __($emptyMessage) }}
                    </h4>
                </div>
            </div>
        </div>
    @endforelse
</div>

{{-- Details MODAL --}}
<div class="modal fade" id="detailsModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
    aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="myModalLabel"> @lang('Details')</h4>
                <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
                    <i class="las la-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <div id="details">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn--dark btn-sm" data-bs-dismiss="modal">@lang('Close')</button>
            </div>
        </div>
    </div>
</div>
{{-- Order MODAL --}}
<div class="modal fade" id="orderModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog ">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">@lang('Place a new order')</h4>
                <button type="button" class="close" data-bs-dismiss="modal">
                    <i class="las la-times"></i>
                </button>
            </div>
            <form method="post" class="resetForm">
                @csrf
                <div class="modal-body">
                    <input type="hidden" name="api_provider_id">
                    <div class="form-group">
                        <label>@lang('Link')</label>
                        <input type="url" class="form-control" name="link" required>
                    </div>
                    <div class="form-group">
                        <label>@lang('Quantity')</label>
                        <input type="number" class="form-control" name="quantity" required>
                    </div>
                    <div class="row">
                        <div class="form-group col-md-6">
                            <div class="input-group">
                                <div class="input-group-text">@lang('Min')</div>
                                <input type="number" name="min" class="form-control" readonly>
                            </div>
                        </div>
                        <div class="form-group col-md-6">
                            <div class="input-group">
                                <div class="input-group-text">@lang('Max')</div>
                                <input type="number" name="max" class="form-control" readonly>
                            </div>
                        </div>
                    </div>
                    <div class="form-group ">
                        <div class="input-group">
                            <div class="input-group-text">@lang('Price')</div>
                            <input type="text" class="form-control total_price " name="price" readonly>
                            <div class="input-group-text">@lang('Per 1K')</div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn--primary h-45 w-100">@lang('Submit')</button>
                </div>
            </form>
        </div>
    </div>
</div>

@endsection

@push('script') (function($) { "use strict";

        $('.detailsBtn').on('click', function() {
            var modal = $('#detailsModal');
            var details = $(this).data('details');
            modal.find('#details').html(details);
            modal.modal('show');
        });

        $('.orderBtn').on('click', function() {
            var modal = $('#orderModal');
            $('.resetForm').trigger('reset');
            var url = $(this).data('url');
            var pricePerK = parseFloat($(this).data('price_per_k'));
            var min = $(this).data('min');
            var max = $(this).data('max');
            let apiProviderId = $(this).data('api_provider_id');
            //Calculate total price
            $(document).on("keyup", "#quantity", function() {
                var quantity = parseInt($('#quantity').val());
                var totalPrice = parseFloat((pricePerK / 1000) * quantity);
                modal.find('input[name=price]').val("{{ $general->cur_sym }}" + totalPrice
                    .toFixed(2));
            });

            modal.find('form').attr('action', url);
            modal.find('input[name=quantity]').attr('min', min).attr('max', max);
            modal.find('input[name=min]').val(min);
            modal.find('input[name=max]').val(max);
            modal.find('input[name=api_provider_id]').val(apiProviderId)
            modal.modal('show');
        });

        $('.favoriteBtn').on('click', function(){
            var $this = $(this);
            var id = $(this).data('id');
            $.ajax({
                type: "GET",
                url: "{{ route('user.favorite.add') }}",
                data: {
                    id : id
                },
                success: function (response) {
                    if(response.action == 'add'){
                        $this.addClass('active');
                    } else {
                        $this.removeClass('active');
                    }
                }
            });
        });
        
        

        //Scroll to paginate position
        var pathName = document.location.pathname;
        window.onbeforeunload = function() {
            var scrollPosition = $(document).scrollTop();
            sessionStorage.setItem("scrollPosition_" + pathName, scrollPosition.toString());
        }
        if (sessionStorage["scrollPosition_" + pathName]) {
            $(document).scrollTop(sessionStorage.getItem("scrollPosition_" + pathName));
        }
    })(jQuery);
</script>

@endpush

0 likes
12 replies
tisuchi's avatar

@fishscale Welcome to Laravel.

Btw, it's not a good idea to load 5000 records on one page (in terms of performance), therefore your page is taking longer to load.

I have been trying to fix three things adding a filter button, search bar and make so the page is paginated where all services is not shown on one page.

I don't suggest this idea to load 5000 on one page! No doubt, it will affect your performance.

You may look into the infinity scroll option which loads all data as long as the user scrolls.

For example: https://infinite-scroll.com/

fishscale's avatar

@tisuchi Yes i know but as i looked on several other websites also using laravel same as mine and have even more services around 10k in one page and the page is instantly loaded with no delay.

I will try and see if i can install infinite scroll.

tisuchi's avatar

@fishscale Do you have any specific website that loads ~10k records on one page?

1 like
fishscale's avatar

@tisuchi smmfollows.com here is an example if you go to services they have 6858 records loaded in one page

tisuchi's avatar

@fishscale I am not so sure what is their technology!

If they use Laravel, they might not just dump everything on one page simply, they may use a different mechanism!

fishscale's avatar

@tisuchi it is laravel because this service smm is famous only for running laravel/php script. I have checked many websites and source codes they are coded with laravel, js, php.

Merklin's avatar

I don't know what your conttroller looks like, but in those cases caching is a must. If you are not using caching. this could be one of the reasons your page is slow.

Also, you can lverage a gzip for the content. There is a package for this: https://github.com/erlandmuchasaj/laravel-gzip

fishscale's avatar

@Merklin Hi rest of my website is very fast its just this specific page services which takes long time and crashes.

Are you talking about this controller.php ?

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Routing\Controller as BaseController; use Laramin\Utility\Onumoti;

class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

public $activeTemplate;

public function __construct()
{
    $this->middleware(function ($request, $next) {
        $this->activeTemplate = activeTemplate();
        return $next($request);
    });

    $className = get_called_class();
    Onumoti::mySite($this, $className);
}

}

Also would you mind explaining short and quick how i can install gzip, im using cpanel hosting i cant run commands there

Merklin's avatar

@fishscale

I meant the controller the collects the data for the $categories and the services.

When loading th categories, despite the caching, you can leverage from the eager loading: https://laravel.com/docs/5.2/eloquent-relationships#eager-loading. Something like:

return Categories::with('services')->get();

If you are using cPanel, the gzip compression should be on and you don't need it separately. You can see if it is on by looking at the headers response send by your website in the browser console.

fishscale's avatar

@Merklin I just checked it wasnt turned on in my cpanel, i turned it on and added this to my .htaccess file now its loading little bit better. It stopped the crashing of browser but still needs >10 sec to load all services. Will check my controller files

"<IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript AddOutputFilterByType DEFLATE application/vnd.ms-fontobject AddOutputFilterByType DEFLATE application/x-font AddOutputFilterByType DEFLATE application/x-font-opentype AddOutputFilterByType DEFLATE application/x-font-otf AddOutputFilterByType DEFLATE application/x-font-truetype AddOutputFilterByType DEFLATE image/jpeg AddOutputFilterByType DEFLATE image/png AddOutputFilterByType DEFLATE image/gif AddOutputFilterByType DEFLATE image/bmp AddOutputFilterByType DEFLATE image/jpeg, AddOutputFilterByType DEFLATE image/svg+xml AddOutputFilterByType DEFLATE image/x-icon AddOutputFilterByType DEFLATE audio/mpeg AddOutputFilterByType DEFLATE audio/* AddOutputFilterByType DEFLATE video/mp4 </IfModule>"

fishscale's avatar

@Merklin I guess this is the code?

public function services() { $pageTitle = 'Services'; $categories = Category::active()->whereHas('services', function ($services) { return $services->active(); })->with('services')->orderBy('name')->get(); $myFavorites = auth()->user()->favorites->pluck('service_id')->toArray(); return view($this->activeTemplate . 'user.services.services', compact('pageTitle', 'categories', 'myFavorites')); }

public function serviceCategory($id)
{
    $category  = Category::active()->findOrFail($id);
    $pageTitle = $category->name;
    $services  = Service::active()->where('category_id', $id)->paginate(getPaginate());
    $myFavorites = auth()->user()->favorites->pluck('service_id')->toArray();
    return view($this->activeTemplate . 'user.services.category', compact('pageTitle', 'services', 'myFavorites'));
}

}

Merklin's avatar

@fishscale In your code you have $services = Service::active()->where('category_id', $id)->paginate(getPaginate()); which I guess takes some time to load, but then you don't use it anywhere on your blade. Instead, you use $category->services

Try this way:

public function serviceCategory($id)
{
    $category  = Category::active()->findOrFail($id)->with('services')->where('services.status', 'active')->paginate(getPaginate());
    $pageTitle = $category->name;
    $myFavorites = auth()->user()->favorites->pluck('service_id')->toArray();
    return view($this->activeTemplate . 'user.services.category', compact('pageTitle', 'services', 'myFavorites'));
}

You have to change ->where('services.status', 'active') though according to your table and column that defines if the service is active or not.

Please or to participate in this conversation.