Pass custom query from controller to view for pagination

Hi there,

I have the following scenario:

On my front-page if have added several flexible content modules with ACF.

In my FrontPage sober controller I loop over these modules to use different Traits to get the appropriate data for these modules:

$query = News::getNews(6);

One of these Traits should return a WP_Query for a custom post type with pagination:

namespace App\Controllers\Traits;

trait News {
	/* Get news items */
	public static function getNews($ppp) {
		$paged = get_query_var('page') ? get_query_var('page') : 1;
		$args  = [
			'post_type'      => 'news',
			'posts_per_page' => $ppp,
			'paged'          => $paged
		];
		$query    = new \WP_Query($args);
		return $query;
	}
}

This Query should be passed over to my blade view so I can loop over it using:

@if ($query->have_posts())
	@while ($query->have_posts())
		@php($query->the_post())
		{{ get_the_title() }}
		... etc
	@endwhile
@endif

However, this results in an error:

ErrorException: Call to undefined method stdClass::have_posts()

So my question, how can I pass over a variable containing my custom query from my sober controller to my blade view?

Thanks!

I do believe that the error is caused by your Trait not being a class. You cannot call methods from it, but instead need to call the method from your FrontPage controller where the Trait is used.

$query = FrontPage::getNews(6);

Thanks for your reply!

The thing is the trait is working fine, because I can print my query in my Blade view just fine, but somehow the have_posts() function doesn’t recognize it as a WP_Query.

When I directly use the Trait in my view like this:

use App\Controllers\Traits\News;
$newsItems = News::getNews(6);

And use the loop like this:

@if ($newsItems->have_posts())
	@while ($newsItems->have_posts())
		@php($newsItems->the_post())
	@endwhile
@endif

The loop works fine?

Try this in your controller.

use App\Controllers\Traits\News;

public function newsItems() 
{
    return $this->getNews(6);
}

Revise your blade file for this variable

@if ($news_items->have_posts())

At any rate, looking at that quirk in your code, I am thinking that is a lot cleaner to go that route. Wasn’t aware you could declare controller properties and have them accessible in a Blade file like that. Double Bonus: the variable is not converted to snake-case either.

I’ve done this kind of thing successfully but I’m not anywhere near my laptop right now to find a reference. What I remember is that I needed to call the controller method statically, as noted in the readme (look for “static methods”).

You need the method to run when you call it from inside the loop, not when the page first starts loading. And as I understand it (and have worked with successfully) that’s what static methods are for.