I writing a plugin to add condition into beforeLoad function of product collection. I set local storage example js to set local storage:

if (typeof(Storage) !== "undefined") {
    // Store
    localStorage.setItem("inventory", "HAN");
    // Retrieve
    document.getElementById("inventory").innerHTML = localStorage.getItem("inventory");

In the magento plugin I want to get inventory value 'HAN' from local storage to use in php class. I wrote the code as below but it can't get inventory in local storage:

    public function beforeLoad(\Magento\Catalog\Model\ResourceModel\Product\Collection $subject, $printQuery = false, $logQuery = false)

        $inventory = "<script>document.write(parseInt(Object.keys(JSON.parse(window.localStorage.getItem('inventory')))))</script>";
        $test = "<script>document.write(localStorage.getItem('inventory'));</script>";

        $joinCondition[] = "e.sku = isi.sku";
        $joinCondition[] = "isi.source_code = '".$inventory."'";
        $joinCondition = implode(' AND ', $joinCondition);
        if (!$subject->isLoaded()) {
            // you can do your customzation/custom logic with $subject object
            //addFieldToFilter('sku', 'MG-854693')
                    [ 'isi' => $subject->getTable('inventory_source_item') ],

        return [$printQuery, $logQuery];

Please help me, How to get inventory value in php class?

Thank you so much, BienHV


localStorage is a javascript variable.You can get localStorage variable value directly at Controller or Any PHP file. You need to use ajax.



  • Thank Amit Bera, I am using cookie to get inventory value. I have other problems with beforeLoad function. 1. This plugin affect to the catalog/product amin page, I want this plugin run only on frontend. How to do that? 2. The beforeLoad function not affect when the page load data from cache. How to fix for this plugin run filter product when load from cache. Thank you so much! Apr 16 '20 at 9:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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