Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

anon34905's avatar

Creating URL´s which include ID and Name

Hello,

is there any way to create URL´s like

http://domain.tld/users/username-1
http://domain.tld/users/1-username
http://domain.tld/users/1/username
http://domain.tld/users/username/1

and so on..

instead of:
http://domain.tld/users/{id]

Any chance to do that, without screwing up my code?

Thanks in advance,

0 likes
6 replies
ChristopherSFSD's avatar

You should be fine adding the username to the URL. If you don't need to use the parameter to locate the user, no big deal it can still be there.

anon34905's avatar

@ChristopherRaymond Thanks! But i´m a little bit lost.

Can you please provide me with a example?

routes.php

Route::resource('articles', 'ArticlesController');

ArticlesController.php

public function show($id)
    {

        $article = Article::findOrFail($id);
        return view('articles.show', compact('article'));
    }

index.blade.php

@extends('app')

@section('content')
<h1>Articles</h1>

<hr/>

  @foreach($articles as $article)
  <article>
    <h2>
      <a href="{{ url('/articles', $article->id) }}">{{ $article->title }}</a>
    </h2>

    <div class="body">{{ $article->body }}</div>

  </article>
@endforeach
@stop

How can i get

http://domain.tld/articles/ID/article-title
ChristopherSFSD's avatar

In your routes, override the route in question. Your routes would look something like this ...

Route::get('articles/{id}/{title}', ['as' => 'article.show', 'uses' => 'ArticlesController@show']);
Route::resource('articles', 'ArticlesController');

Then in your template ...

<a href="{{ route('article.show', [$article->id, urlencode($article->title)]) }}" ...

Just make sure you put the new route ABOVE the existing one.

1 like
anon34905's avatar

Works like a charm!

One last question: How can i replace the plus-sign in my links with a dash? ( - )

alainbelez's avatar

if you want dash. maybe use str_slug($article->title)

1 like

Please or to participate in this conversation.