laravelseocanonical-link

Laravel previous and next page into controller


I'm using this Laravel SEO package artesaos/seotools.

Is there a way for get prev and next page for pagination in controller?

function seoMetaDetail($detail)
{
    SEOMeta::setCanonical(request()->fullUrl());         
    SEOMeta::setPrev(''); <-- previous page
    SEOMeta::setNext(''); <-- next page
}

Solution

  • You can get the current page from the query string.

    function seoMetaDetail($detail)
    {
        $current = request()->query('page');
    
        SEOMeta::setCanonical(request()->fullUrl());
        // If there's no current, then we're on page 1. return null. Otherwise current - 1
        SEOMeta::setPrev($current ? ($current - 1) : null);
        // If there's no current, then we're on page 1, return 2. Otherwise current + 1
        SEOMeta::setNext($current ? ($current + 1) : 2);
    
    }
    

    You can also use the paginator methods.

    public function seoMetaDetail($detail)
    {
        $paginator = YourModel::query()->....->paginate();
    
        SEOMeta::setCanonical(request()->fullUrl());
        SEOMeta::setPrev($paginator->previousPageUrl());
        SEOMeta::setNext($paginator->nextPageUrl());
    }
    

    https://laravel.com/docs/9.x/pagination#paginator-instance-methods