0
votes

I am new in Laravel How can I add pagination to getRelatedNews function I need to display simple "Next" and "Previous" links in pagination view, I try to use simplePaginate method I don't know where to put the function ?

public function news($id, $alias)

{
    $crypto_news = CryptoNews::where('id', $id)->first();
    if(isset($crypto_news->title)) {
        $data = [
            'crypto_news' => $crypto_news,
            'crypto_related_news' => $this->getRelatedNews($id,100),
            'crypto_most_read_news' => $this->getMostReadNews($id, 7, 6),
            'crypto_news_from_bitcoin' => $this->getNewsFromBitcoin($id, 9)
        ];
        return view(getCurrentTemplate() . '.pages.single_news', $data);
    }
    return redirect('/crypto-coins-news-headlines');
}

public function getRelatedNews($id, $limit)
{
    $crypto_news = CryptoNews::take($limit)
        ->where('status', '=', 1)
        ->where('urlToImage', '!=', 'no_preview.png')
        ->where('urlToImage', '!=', '')
        ->where('lang', 'en')->where('id', '!=', $id)
        ->orderBy('publishedAt', 'desc')->get()->toArray(); 
    $lang_news = [];            
    if(LaravelLocalization::getCurrentLocale() != 'en') {
        $news_object = CryptoNews::take($limit)
            ->where('status', '=', 1)
            ->where('urlToImage', '!=', 'no_preview.png')
            ->where('urlToImage', '!=', '')->where('id', '!=', $id)
            ->where('lang', LaravelLocalization::getCurrentLocale())
            ->orderBy('publishedAt', 'desc');
        if($news_object->count() > 0) {
            $lang_news = $news_object->get()->toArray();
        }
        if($news_object->count() > $limit) {
            $crypto_news = $lang_news;
        } else {
            $crypto_news = array_merge($lang_news, array_slice($crypto_news, 0, $limit-$news_object->count()));
        }
    }
    return $crypto_news;
}
1
laravel.com/docs/8.x/pagination please refer to this link. Hope you get your solution from official doc. You have to add only paginate() method in query response.Jaynil Savani
I am getting this error (2/2) ErrorException A non well formed numeric value encountered after i use $crypto_news = CryptoNews::where('status', '=', 1) ->where('urlToImage', '!=', 'no_preview.png') ->where('urlToImage', '!=', '') ->where('lang', 'en')->where('id', '!=', $id) ->orderBy('publishedAt', 'desc')->simplePaginate($limit);muhammed alsmawi

1 Answers

0
votes

If you're implementing the pagination, you don't need the take() method. Quoting from the official docs:

The take method returns a new collection with the specified number of items.

To use simplePaginate, you can use it like this in your query:

$crypto_news = CryptoNews::where('status', '=', 1)
    ->where('urlToImage', '!=', 'no_preview.png')
    ->where('urlToImage', '!=', '')
    ->where('lang', 'en')->where('id', '!=', $id)
    ->orderBy('publishedAt', 'desc')->simplePaginate($limit);