I want to create a Store programatically, but if it already exists, then return the existing store. So far my code looks like this:

private function _getStore($website, $storeName, $storeCode)
    try {
        if ($store = $this->storeRepository->get($storeCode)) {
            $groupId = $store->getStoreGroupId();
            return $this->groupRepository->get($groupId);
    } catch (\Exception $e) {}

    if ($website->getId() && !empty($storeName) && !empty($storeCode)) {
        /** @var \Magento\Store\Model\Group $group */
        $group = $this->groupFactory->create();
        return $group;
    return null;

When I create the store for the first time with the store code my_store it works fine; I can see that it is logged in store_group table.

The second time I run it I am expecting it to give me the store thanks to $this->storeRepository->get($storeCode) but it doesn't find the store... I know this because if I remove the try/catch it will return an exception:

The store that was requested wasn't found. Verify the store and try again.

So how would I check if the store already exists by code?

Can someone please explain the difference between store and group?

1 Answer 1


How would I check if the store already exists by code?

Your approach is correct.

Example Code :

try {
} catch (NoSuchEntityException $nsee) {
    // Requested store doesn't exist

Difference between store and group

If you will see grid under Stores -> All Stores, you will see three columns Web Site, Store and Store View
Web Site is mapped to the store_website table in the database.
Store is mapped to the store_group table in the database.
Store View is mapped to the store table in the database.

So, the $group is nothing but the store_group which is the representation of the store entity only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.