Magento, Magento 2

How to check current area code in Magento 2

How to check current area in Magento 2

In this tutorial, I will explain to you how to check the current area code in Magento 2. Sometimes, it may be required to develop functionality based on the area like only for the frontend side or only for the backend side.

When we need to execute script from the root folder at that time, how can we detect the current area of Magento 2? We can check the current area of Magento 2 using two methods.

  1. Object Manager Method.
  2. Construct Method.

You may also like this :

First of all, Let’s assume that you have already created module.

1. Object Manager Method :

/**
 * Created By : Rohan Hapani
 */
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$state = $objectManager->get('Magento\Framework\App\State');
echo $state->getAreaCode(); // Output Like : frontend, backend or webrest_api

Note: Avoid using the object Manager method in your module. Use always construct method.

2. Construct Method :

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Block;

use Magento\Framework\App\State;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;

class AreaCode extends Template
{
    /**
     * @var State
     */
    protected $state;

    /**
     * @param Context $context
     * @param State   $state
     * @param array   $data
     */
    public function __construct (
        Context $context,
        State $state,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->state = $state;
    }

    public function getArea()
    {
        return $this->state->getAreaCode();
    }
}

Now, you can use this block in your layout or construct and get area code by getArea() function.

That’s it !!

I hope this blog will helpful for easily understand how to check the current area code in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Keep liking and sharing 🙂
Tagged ,