Getting posts from an array in blade partial

Hi,

I tried the advice here to separate the template’s logic into a controller. var_dump($data) in App.php outputs the data from the correct pages, but I can’t get the partial to display the posts.

Here’s my code:

App.php:

public function getMenuPages()
{

$args = array(
    'post_type'         => 'page',
    'posts_per_page'    => 3,
    'post_parent'       => 0,
    'orderby'           => 'menu_order',
    'order'             => 'DESC'
);
$result = new \WP_Query($args);

$data = array_map(
    function( $post ) {
        return (array) $post;
    }, $result->posts);
}

and the partial:

@if($get_menu_pages)
   @foreach($get_menu_pages as $post)
            <div>
                ...
            </div>
   @endforeach
@endif

Thanks in advance for any tips etc :thinking:

getMenuPages() is missing a return statement like return $data; .

2 Likes

Thanks! In my partial var_dump($post) in my partial now shows arrays of the post data. The only way I could figure out how to use the data was like this:

		@php $object = (object) $post @endphp
		{{ $object->post_title }}

I’m guessing that I need to get $data passed as an object somehow, do you know how to do that? Sorry be a nuisance

You would do it exactly as you did above, just in the controller

1 Like

If you want each post to be represented as an object instead of an array, you can remove the $data = array_map(... stuff since that is what is creating the array-representation of each post.

So you would end up with something like this:

public function getMenuPages()
{

  $args = array(
    'post_type'         => 'page',
    'posts_per_page'    => 3,
    'post_parent'       => 0,
    'orderby'           => 'menu_order',
    'order'             => 'DESC',
  );

  return (new \WP_Query($args))->posts;

}
1 Like

Thank you very much @folbert and @alwaysblank. That was exactly the help I needed to tie everything together. Here’s my final working code if anyone in the future needs help making a controller to get post data for a blade template:

Controller (App.php in my case):

public function fooBar()
{

$args = array(
    'post_type'         => 'page',
    'posts_per_page'    => 3,
     ...
);
$result = new \WP_Query($args);

$data = array_map(
    function( $post ) {
        return array (
        'title'   => $post->post_title,
        ...
        );
    }, $result->posts);
    return $data;
}

Partial:

@if($foo_bar)
   @foreach($foo_bar as $post)          
            <div class="...">
            <p><a href="#" class="...">{{ $post['title'] }}</a></p>
            </div>
   @endforeach
@endif

Thanks again!

This topic was automatically closed after 42 days. New replies are no longer allowed.