2

how to check if the target path for custom url is present in the url rewrite table in magento 2.

I had created custom url rewrite using following code.

$urlRewriteModel = $this->_urlRewriteFactory->create();
$urlRewriteModel->addData(
            [
                'entity_type' => \Magento\UrlRewrite\Controller\Adminhtml\Url\Rewrite::ENTITY_TYPE_CUSTOM,
                'entity_id' => 0,
                'request_path' => "abc",
                'target_path' => "xyz/index/view/id/".$displayText['videoData']['id'],
                'redirect_type' => \Magento\UrlRewrite\Model\OptionProvider::PERMANENT,
                'store_id' => 1,
                'description' => null,
                'is_autogenerated' => 0,
                'metadata' => null
            ]
        );
$urlRewriteModel->getResource()->save($urlRewriteModel);

This data add when i save any new record in from admin. if i edit same record then also it will call. so i want to know if that target record is already ther in magento 2. if yes delete and add again using above code.

2 Answers 2

6
protected $_urlRewrite;

public function __construct(
    \Magento\UrlRewrite\Model\UrlRewrite $urlRewrite
) {
    $this->_urlRewrite = $urlRewrite;
}



    $UrlRewriteCollection=$this->_urlRewrite->getCollection()->addFieldToFilter('target_path', 'path_to_check')
    $deleteItem = $UrlRewriteCollection->getFirstItem(); 
    if ($UrlRewriteCollection->getFirstItem()->getId()) {
        // target path does exist
        $deleteItem->delete();
    }
3
  • i want to delete if target path exists Commented Oct 12, 2018 at 10:31
  • Please check updated answer. I didn't test. Commented Oct 12, 2018 at 10:38
  • Upvote the answer so it will be helpful to other also. Commented Oct 12, 2018 at 11:27
0

The current answer is great, but using interfaces is always the best

Try using the following code:

public function __construct(
   \Magento\UrlRewrite\Model\UrlFinderInterface $urlFinder
) {
   $this->urlFinder = $urlRewrite;
}

...

$data = [
   \Magento\UrlRewrite\Service\V1\Data\UrlRewrite::REQUEST_PATH => 'requst_path',
   \Magento\UrlRewrite\Service\V1\Data\UrlRewrite::TARGET_PATH => 'target_path',
   \Magento\UrlRewrite\Service\V1\Data\UrlRewrite::STORE_ID => 'storeId',
];

$url = $this->urlFinder->findOneByData($data); // returns null if not found

I hope this answer will help someone in the future.

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.