Displaying blog posts on home/index page



  • Hi,

    Is there anyway to display the posts of the blog on the index/home page?

    I noticed the documentation saying there is a $posts variable but only on the blog index page.

    How could you get this in the home page to display the latest blog posts?

    Thanks


  • Global Moderator

    @Fremster

    Well you would have to collect data for yourself in controller. You would extend Pages public controller in your module and override homepage method (or you can hardcode in Pages module for testing :D).

    You would then do something like that:

    1. Inject way
    use Modules\Blog\Repositories\PostRepository;
    
    public function homepage(PostRepository $blogPostRepository)
    {
            $latestPosts = $blogPostRepository->latest(5);
    }
    
    1. Without inject
    public function homepage()
    {
            // $blogPostRepository = app(Modules\Blog\Repositories\PostRepository::class);
            $blogPostRepository = $this->app->make('Modules\Blog\Repositories\PostRepository');
            $latestPosts = $blogPostRepository->latest(5);
    }
    

    Both ways will return collection of Posts for current locale.



  • Thanks for the reply. I will take a better look at this, but in the meanwhile I did a hacky version, which well works but I am not sure its the best way.

    From the home page view I made an ajax call to the /blog/posts and returned the specific div with the data i needed:

    <script type="text/javascript">
    	$.ajax({
    	  url: "./en/blog/posts",
    	  cache: false,
    	  'dataType': 'html',
    	  success: function(data){
    	  	console.log(data);
    	    $("#results").html($("#datainfo",$(data)).html());
    	  }
    	});
    </script>
    

    This however gave an issue with the return view as I didn't want the same layout in the home view as the blog view. 1 way i could figure out how to make them difference was to check if it was an xmlhttprequest, and if it was I knew it was the home page requesting, so I could return that specific view.

    public function index()
    {
        $posts = $this->post->allTranslatedIn(App::getLocale());
    
        if (strtolower(filter_input(INPUT_SERVER, 'HTTP_X_REQUESTED_WITH')) === 'xmlhttprequest') {
           return view('blog.home', compact('posts'));
        }
    
        return view('blog.index', compact('posts'));
    }

  • Global Moderator

    @Fremster That's another way to do it :)
    You could use laravels detection if(Request::ajax())


Log in to reply