Magento: Programmatically Remove Layout Block

This article shows how you can remove layout blocks through the PHP Program instead of working in the layout.xml file in Magento 2.

I will be using event observer.

app/code/Company/Module/etc/frontend/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="layout_generate_blocks_after">
        <observer name="remove_block" instance="Company\Module\Model\Observer\RemoveBlock" />
    </event>
</config>

app/code/Company/Module/Observer/RemoveBlock.php

Here, I am checking if a customer is logged in or not & removing the layout block if the customer is not logged in.

<?php

namespace Company\Module\Model\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Http\Context as HttpContext;

class RemoveBlock implements ObserverInterface
{
    /**
     * @var HttpContext
     */
    protected $httpContext;

    public function __construct(
        HttpContext $httpContext
    ) {
        $this->httpContext = $httpContext;
    }

    public function execute(Observer $observer)
    {
        /** @var \Magento\Framework\View\Layout $layout */
        $layout = $observer->getLayout();

        $isCustomerLoggedIn = (bool)$this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
        
        if (!$isCustomerLoggedIn) {
            $blockName = 'your-block-to-remove';
            $block = $layout->getBlock($blockName);
            if ($block) {
                $layout->unsetElement($blockName);
            }
        }
    }
}

Hope this helps. Thanks.