Tag Archives: Magento 2 tutorial
Magento 2 Core read write Query
Magento 2 Core read write Query– We sometimes need to run core queries in Magento 2 to perform some specific task. To run custom query we can use object manager or dependency injection. Here in this tutorial, we are going to cover the both method to run the raw query.
Magento 2 Core read write Query | Run Direct SQL Example
Magento 2 allows us to run the core query which can be used to read or write data. –
Method 1
Import resource(\Magento\Framework\App\ResourceConnection) in class simply as below –
protected _resource; public function __construct(Context $context, \Magento\Framework\App\ResourceConnection $resource) { $this->_resource = $resource; parent::__construct($context); }
Get resource connection-
$connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);
Now run your custom query-
Read Query
Fetch All Result
You can select all data from table using custom query simply as below-
$connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION) $orderTable = $connection->getTableName('sales_order'); $result1 = $connection->fetchAll('SELECT * FROM '.$orderTable.' WHERE entity_id='.$orderId);
Run raw Query– If you want to run the raw query you can run it simply as below-
$connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION) $result1 = $connection->query('SELECT * from users where user_id = 100');
Write Query
You can insert/update/delete the data using core query simply as below-
Insert
$connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION) $connection->query('INSERT into users(1, 'test user', 'test@yopmail.com')');
Update
$connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION) $connection->query(' UPDATE users set name="Jhon" where id="10"');
Delete
$connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION) $connection->query(' DELETE from users where id="10"');
Method 2- Using Object Manager
Using Object Manager You can run custom query simply as below-
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $resource = $objectManager->get('Magento\Framework\App\ResourceConnection'); $connection = $resource->getConnection(); $table = $resource->getTableName('users'); //Select Query Example $result = $connection->fetchAll("Select * FROM " . $table); // returns array. //Insert Query $connection->query("Insert Into " . $table . " (name, email, phone) values ('Jhon','jhon@example.com','123123123')"); //Update Query $sql = "Update " . $table . "Set email = 'abc@example.com' where id = 19"; $connection->query($sql); //Delete Query Example $connection->query("Delete FROM " . $table." Where id = 99");
On the same way you can perform read/write ie you can run direct sql query using any one method in Magento 2.
Magento 2 Create Customer Programmatically
Magento 2 Create Customer Programmatically Sometimes we need custom code to create customer such as creating custom regirstration page or creating some custom customer import functionality. Here in this article, we are going to explain how you can create customer using custom program.
Magento 2 Create Customer Programmatically Example
You can create customer in Magento2 using custom code simply as below-
Magento 2 Create Customer Programmatically Example:
storeManager = $storeManager; $this->customerFactory = $customerFactory; parent::__construct($context); } public function execute() { // Get Current Website ID $websiteId = $this->storeManager->getWebsite()->getWebsiteId(); $customer = $this->customerFactory->create(); $customer->setWebsiteId($websiteId); $customer->setEmail("john@example.com"); $customer->setFirstname("John"); $customer->setLastname("Dee"); $customer->setPassword("123XYZ"); $customer->save(); $customer->sendNewAccountEmail(); } } ?> |
So you can create customer in Magento2 programmatically.
Magento 2 Get out of stock Products
Magento 2 Get out of stock Products– We can use product collection and joinField to get the out of stock items. Here in this tutorial, we are going to explain how you can get out of stock items in Magento2.
Magento 2 Get out of stock Products Collection Query xample
You can get out of stock items in Magento 2 Simply as below-
Magento 2 Get out of stock Products Example:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $productCollectionFactory = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory'); $productCollection = $productCollectionFactory ->create() ->addAttributeToSelect('*') ->addAttributeToSort('created_at', 'DESC') ->joinField('stock_item', 'cataloginventory_stock_item', 'qty', 'product_id=entity_id', 'qty=0') ->setPageSize(10) ->load(); |
The above example will give you list of items that are not in stock.
Magento 2 Logout Customer Programmatically
Magento 2 Logout Customer Programmatically– Sometimes we need to logout customer programmatically based upon some condition or validation. Here in this article we are going to explain how you can logout customer from block, controller, model, observer or anywhere.
Magento 2 Logout Customer Programmatically Example
You can use object manager to logout customer session simply as below –
Magento 2 Logout Customer Programmatically Example:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $customerSession = $objectManager->create('Magento\Customer\Model\Session'); if($customerSession->isLoggedIn()) { $customerSession->_logout(); echo "Logged Out Successfully!"; } |
The above example will logout the current customer session.
Magento 2 Left Join Collection Query
Magento 2 Left Join Collection Query ->joinLeft() is used for left join with collection in magento 2. It is very simple to use ->joinLeft(), left join returns all data from left table and the matching records from right table. Here in this tutorial we are going to create very simple and basic example of left join in Magento 2.
Magento 2 Left Join Collection Query | Example
Here we have created an example for left join with order table and order_item table, which will pull the data based on left join query-
Magento 2 Left Join Collection Query | Example:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $collection = $objectManager->get('Magento\Sales\Model\Order')->getCollection(); $collection->getSelect() ->joinLeft( array('order_item'=> 'sales_order_item'), 'order_item.order_id = main_table.entity_id', array('order_item.sku')); |
On the same way you can use left join with multiple tables.
Magento 2 Join Collection Query
Magento 2 Join Collection Query It is a little bit different to join the multiple tables with collection in magento 2 than the magento 1.x. Here in this tutorial we are going to create very simple and basic example of join in Magento 2.
Magento 2 Join Collection Query | Join Multiple Tables Example
Here we have created one example to join the order table with order_item table which will pull the data based on join query-
Magento 2 Join Collection Query | Example:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $collection = $objectManager->get('Magento\Sales\Model\Order')->getCollection(); $collection->getSelect()->join( array('order_item'=> 'sales_order_item'), 'order_item.order_id = main_table.entity_id', array('order_item.sku')); |
On the same way you can join multiple tables.
Magento 2 get Customer Details
Magento 2 get Customer Details– It is totally different to get the customer details in Magento 2. You can use object manager or service contracts(\Magento\Customer\Api\CustomerRepositoryInterface). Here in this tutorial we are going to explain how to get customer details using customer id or customer session. We will cover the other details like -email, name, shipping address, billing address details etc.
Magento 2 get Customer Details Example
First of all, we need to get the customer object either by session or load customer by id. Let us go one by one-
Load Customer Data By Id
You can use object manager to load the customer by id simply as below –
Magento 2 get Customer Details Example:
$customerId = 101; $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $customer = $objectManager->create('Magento\Customer\Model\Customer')->load($customerId); |
Get Customer Data From Session
If customer is logged in you can get the customer object from session using object manager simply as below-
Magento 2 Get Customer Session Example:| Get current customer Id
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $customerSession = $objectManager->get('Magento\Customer\Model\Session'); if($customerSession->isLoggedIn()) { $customer = $customerSession->getCustomer(); $id = $customer->getId(); // customer Id } |
Using the above method you can check whether customer is logged in or not. Now let us get more details about the customer using the above customer object.
- Customer Id
- Customer Name(FirstName, LastName)
- Customer Email Id
- Customer Group Id
Get Customer Id | First Name | Last Name | Email Id | Customer Group Id
Get Customer Data in Magento 2 Example:
$customerId = 101; $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $customer = $objectManager->create('Magento\Customer\Model\Customer')->load($customerId); $firstname = $customer->getFirstname(); $lastname = $customer->getLastname(); $email = $customer->getEmail(); $groupId = $customer->getGroupId(); |
The above example will give you the customer details.
Get Customer Address Details
- Default Shipping Address Details
- Default Billing Address Details
Get Shipping Address Details | By Default Address Id
Customer’s Default Shipping Address Can Be Loaded Using the Default Address Id. You can get the following shipping details from Shipping Address Object-
- Shipping FirstName
- Shipping LastName
- Shipping Company
- Shipping Zip Code
- Shipping City
- Shipping Street
- Shipping Telephone
- Shipping Country
Load Customer Address By Address Id Example:
$shippingAddressID = $customerSession->getCustomer()->getDefaultBilling(); $shippingAddress = $objectManager->create('Magento\Customer\Model\Address')->load($shippingAddressID); $shippingFirstname = $shippingAddress->getFirstname(); $shippingLastname = $shippingAddress->getLastname(); $shippingCompany = $shippingAddress->getCompany(); $shippingZipcode= $shippingAddress->getPostCode(); $shippingCompany = $shippingAddress->getCompany(); $shippingStreet = $shippingAddress->getStreet(); $shippingStreet1 = $shippingStreet[0]; $shippingStreet2 = $shippingStreet[1]; $shippingTelephone = $shippingAddress->getTelephone(); $shippingFax = $shippingAddress->getFax(); $shippingCountry = $shippingAddress->getCountry(); |
Get Billing Address Details | By Default Address Id
Customer’s Default Billing Address Can Be Loaded Using the Default Address Id. You can get the following shipping details from Billing Address Object-
- Billing FirstName
- Billing LastName
- Billing Company
- Billing Zip Code
- Billing City
- Billing Street
- Billing Telephone
- Billing Country
Load Customer Billing Address By Billing Id Example:
$shippingAddressID = $customerSession->getCustomer()->getDefaultBilling(); $billingAddress = $objectManager->create('Magento\Customer\Model\Address')->load($shippingAddressID); $billingFirstname = $billingAddress->getFirstname(); $billingLastname = $billingAddress->getLastname(); $billingCompany = $billingAddress->getCompany(); $billingZipcode= $billingAddress->getPostCode(); $billingCompany = $billingAddress->getCompany(); $billingStreet = $billingAddress->getStreet(); $billingStreet1 = $billingStreet[0]; $billingStreet2 = $billingStreet[1]; $billingTelephone = $billingAddress->getTelephone(); $billingFax = $billingAddress->getFax(); $billingCountry = $billingAddress->getCountry(); |
Magento2 get current Category
Magento2 get current Category- In magento 2 the way to get the current category has been changed. You can use object manager to get the current category detail in magento2. Here in this tutorial we are going to explain how you can access the current category in magento 2.
Magento2 get current Category
You can get the current category detail in magento 2 using the object manager as below –
Magento2 get current Category :
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category'); echo $catId = $category->getId(); //$catName = $category->getName(); |
The above example will give you the current category details. You can access other details same as we have shown the category id and name.