Laravel route with id and name

10,751

You cant do routing like

{head}-{id}

You need to do this:

Route::get('/field/{head}/{id}', 'FieldsController@show');

Then in your show() function you can combine them yourself:

function show($head, $id)
{
     $var = $head.'-'.$id;
     // do whatever you want with $var here
}
Share:
10,751
Aleš Chromec
Author by

Aleš Chromec

Updated on June 04, 2022

Comments

  • Aleš Chromec
    Aleš Chromec almost 2 years

    I generate URL like this:

    URL::action('FieldsController@show',['id' => $field->id, 'head' => cleanUrl($field->head)])
    

    In my routes I have:

    Route::get('/field/{head}-{id}', 'FieldsController@show');
    

    And it dont work, only when I put ID first and HEAD second like this:

    Route::get('/field/{id}-{head}', 'FieldsController@show');
    

    Anyone have ideas? I need to have ID after HEAD in URL

  • Laurence
    Laurence about 9 years
    In your controller. Your route is called FieldsController@show - so it is saying it is using a show() function?
  • Aleš Chromec
    Aleš Chromec about 9 years
    Oh, my mistake.. Now I understand. Thank you for that.
  • Ravan Scafi
    Ravan Scafi about 9 years
    @TheShiftExchange why a route can't be done like that?
  • Laurence
    Laurence about 9 years
    @Ravan - You cannot safely split variables by - in the url. There are issues with trying it that way when Laravel tries to parse the route and determine which text belongs in which variable. Using / is only safe way to ensure the correct text ends up in the correct variable when parsing. For example - if someone types /field/this-is-an-example - which variables go where? It is impossible for Laravel to determine using the original design. But this works: /field/this-is/an-example