How To Pass Parameter To URL In Magento 2 Programmatically

To pass a parameter to URL in Magento 2 follow this method

Create Data.php

Directory

app\code\VendorName\ModuleName\Helper\Data.php

Content of Data.php

<?php
namespace VendorName\ModuleName\Helper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\UrlInterface;
class Data extends AbstractHelper
{
    protected $urlBuilder;
    
    public function __construct(
        Context $context,
        UrlInterface $urlBuilder
    )
    {
        $this->urlBuilder = $urlBuilder;
        parent::__construct($context);
    }
    public function GetParamUrl()
    {
        $queryParams = [
            'param_1' => value1, // value for parameter
            'param_2' => value2
        ];
        
       return $this->urlBuilder->getUrl('route/controller/action', ['_current' => true,'_use_rewrite' => true, '_query' => $queryParams]);
      //Ex: $this->urlBuilder->getUrl('custom/addcart/index', ['_current' => true,'_use_rewrite' => true, '_query' => $queryParams]);
    }
}

If you are using phtml file, use this code

$block->getUrl('route/controller/action',['param'=>'value'])
We are providing the best Magento 2 Extensions at the lowest prices.
Related Products