skip to Main Content

I have a problem with laravel routes.

I had an old store in php and i rewrite it in laravel. The problem is with the products route. They have been indexed (google) and now those links i can`t access them.

The url structure was:

http://mydomain/product/{productName}-{productID}.html

In laravel i created a route to generate the same structure:

Route::get('/product/{productName}-{id}.html', 'ProductController@index')->name('product');

The problem is when an old url contains a dot (.) in productName it returns 404 (does not enter in Controller) – because of the (.html) in the new route.

If remove the (.html) from route i get the request in controller, but how can I better create the structure of the url?

/{productName}-{productID}.html

UPDATE

when generating the productName i use a php function to make it seo (productName):

public function makeSeoLink($string)
{
    // trim the string
    $string = trim($string);

    // remove all diacritics
    $string = str_ireplace(array("â", "î", "ă", "ș", "ț"), array("a", "i", "a", "s", "t"), $string);

    // remove all non alphanumeric characters except spaces
    $clean =  preg_replace('/[^a-zA-Z0-9s]/', '', strtolower($string));

    // replace one or multiple spaces into single dash (-)
    $clean =  preg_replace('!s+!', '-', $clean);

    return $clean;
}

when generating the url:

route('product', array(makeSeoLink($p->Name), $p->id));

2

Answers


  1. For Laravel there is a where clause for routes. So you can add an extension and in the where clause specify it. Here is an example.

    Route::get('/product/{productName}-{id}{extension}', 'ProductController@index')->name('product')->where('extension', '(?:.html)?');
    

    I got this answer from here.

    Other useful links

    https://stackoverflow.com/a/22289143/6261137

    https://stackoverflow.com/a/33827159/6261137

    Login or Signup to reply.
  2. since product name can contain dash(-) you have to use something like this:

    Route

    Route::get('/product/{productDetails}','ProductController@index')->name('product');
    

    index function

    function index(){
        $segment = Request::segment(2);
        $segment = str_replace('.html', '', $segment);
        $list =  explode('-',$segment);
        $id = end($list);
        array_pop($list);
        $text = implode("-",$list);
        return [$id,$text];
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search