Check below step If you want to display out of stock products at last on product listing page in Magento 2.
You need to develop a custom extension (Here, I’m assuming that you know how to create custom extension in Magento 2).
We need to use MagentoCatalogSearchModelResourceModelFulltextCollection for product collection.
1. Create app/code/Magemonkeys/OutOfStockAtLast/etc/di.xml and add below code.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="MagentoCatalogSearchModelResourceModelFulltextCollection">
<plugin name="Magemonkeys_OutOfStockAtLast::OutofstockLast" type="MagemonkeysOutOfStockAtLastPluginProductProductListToolbar"/>
</type>
</config>
2. Create app/code/Magemonkeys/OutOfStockAtLast/Plugin/Product/ProductList/Toolbar.php and add below code.
<?php
namespace MagemonkeysOutOfStockAtLastPluginProductProductList;
class Toolbar
{
public function beforeLoad(
MagentoCatalogSearchModelResourceModelFulltextCollection $subject,
$printQuery = false,
$logQuery = false
)
{
$order = $subject->getSelect()->getPart(Zend_Db_Select::ORDER);
$oosorder = array('is_salable DESC');
$subject->getSelect()->reset(Zend_Db_Select::ORDER);
$subject->getSelect()->order($oosorder);
return [$printQuery, $logQuery];
}
}
There you go. I hope following above steps will let you display out of stock product at last on catalog page in Magento 2.
Happy coding!

