How to get customer data by customer email in magento 2?

You can get customer information by just passing the customer email using below code snippet, Create Block file,

To Fetch Customer Data in Magento by customer email ID, you required a customer email id and an optional website id to fetch the correct data.

<?php
declare(strict_types=1);

namespace Rbj\Customer\Model;

use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;

class CustomerDetail
{
    public function __construct(CustomerRepositoryInterface $customerRepository )
    {
        $this->customerRepository = $customerRepository;
    }

    /**
     * @param string $email
     * @param ?int $websiteId
     * @return CustomerInterface
     * @throws LocalizedException
     */
    public function getCustomerByEmail(string $email, int $websiteId = null): CustomerInterface
    {
        try {
            $customer = $this->customerRepository->get($email, $websiteId);
        } catch (NoSuchEntityException $exception) {
            throw new LocalizedException(__('Provided Customer no longer exists.'));
        }
        
        return $customer;
    }
}

Continue reading “How to get customer data by customer email in magento 2?”

How to get remote address in magento 2 way?

Get the Remote address IP by Magento 2 with a simple code snippet,

<?php
public function __construct(
    \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress $remoteAddress
    ) {
    $this->_remoteAddress = $remoteAddress;
}
public function getRemoteAddress(){
    $remoteAddress = $this->_remoteAddress->getRemoteAddress();
    return $remoteAddress;
}

Call function in template file by below way,

echo $this->getRemoteAddress();

How to get product collection by product id in magento 2?

You can get product data by product id in Magento 2 by below code snippets,

<?php

namespace Rbj\Training\Block;

class Product extends \Magento\Framework\View\Element\Template
{
    /**
     * Constructor
     *
     * @param \Magento\Framework\View\Element\Template\Context  $context
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        array $data = []
    ) {
        $this->productRepository = $productRepository;
        parent::__construct($context, $data);
    }

    /**
    * Get Product by Id
    * @param int
    * @return \Magento\Catalog\Model\Product $product
    */
    public function getProduct($id)
    {
        return $this->productRepository->getById($id);
    }
}

Call inside template file by below code,

$product_id = 1;
$product = $block->getProduct($product_id);
echo $product->getName(); // product name
echo $product->getSku(); // product sku