How To get the collection from the ViewModel

Package name : Tridhya
Module : Blog
For fetching the data or getting the collection of the table we can use the ViewModel. Below is a short example that how we can fetch the collection data from the viewmodel

  • Declare view model in the layout file

<?xml version="1.0"?>
<page xmlns:xsi="" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<referenceContainer name="content">
<block class="Magento\Framework\View\Element\Template" name="blog.list" template="Tridhya_Blog::blog.phtml">
<argument name="view_model" xsi:type="object">Tridhya\Blog\ViewModel\Data</argument>

  • Create pltml file in path: app\code\Tridhya\Blog\view\frontend\templates\blog.phtml from the file we can load the view model with the name which we have passed in the arguments “view_model”


$viewModel= $block->getData('view_model');
$blogs = $viewModel->getCollection();


  • Create a file in path : app\code\Tridhya\Blog\ViewModel\Data.php


    namespace Tridhya\Blog\ViewModel;

class Data implements \Magento\Framework\View\Element\Block\ArgumentInterface
protected $blogFactory;

public function __construct(
\Tridhya\Blog\Model\BlogFactory $blogFactory
) {
$this->blogFactory = $blogFactory;

public function getCollection() {
$blogFactory = $this->blogFactory->create();
$collection = $blogFactory->getCollection();
return $collection;

I hope this has helped you understand how we can fetch the collection data from the viewmodel. If you have any questions we are here to help. Get in touch with us!

This blog is written by , Jainil Khamar – Sr. Software Engineer at TridhyaTech