How to fetch current stock id value from current website in Magento 2?

Magento with multiple stocks available at the website level and if you want to get the current stock ID value dynamically in Magento, you can fetch the value by using Magento inventory module functionality.

Retrieving stock ID will be helpful while you are using multi-source functionality in your website.

Let’s say your stock ID name is UK-stock (ID: 4) and you want to fetch the ID at any specific place in your code level, You can get it by using the GetStockIdForCurrentWebsite class.

<?php
declare(strict_types=1);

namespace Rbj\Stock\Model;

use Magento\InventoryCatalog\Model\GetStockIdForCurrentWebsite;

class PickupStore
{
    public function __construct(
        private readonly GetStockIdForCurrentWebsite $getStockByWebsite
    ) {
    }

    public function getStockIdFromCurrentWebsite(): int
    {
        return $this->getStockByWebsite->execute();
    }
}

You can retrieve the stock id value from the current website id using the above approach.

Your output will be 4  in the above case while you are inside a website that has UK stock as your preferred stock.