Magento2 URL Rewrite – How to Check if Target Path Exists

magento2url-rewrite

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.

Best Answer

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();
    }