Search code examples
phplaravelslug

Laravel "{slug}" not being replaced, instead being url encoded


I've recently embarked on learning Laravel. In doing so I've began completing tutorials from around the web, including from youtube. In one such tutorial I've been developing a very basic blog. I've hit something of an impasse when working with slugs. For some reason, it just doesn't want to work for me!

When the following code is entered in my 'routes.php' file, I have noticed that the braces '{' and '}' are automatically converted to URL encoding and the word "slug" is displayed. Additionally, the '/' following the word posts is nowhere to be seen. This means a link will read as "http:[domain name]/posts/%7Bslug%7D[article name]"

Route::get('/posts/{slug}', [
    'as' => 'post-show', 
    'uses' => 'PostController@getIndex'
]);

The problem is partially resolved if I change the code thus:

Route::get('/posts/{slug?}', [
    'as' => 'post-show', 
    'uses' => 'PostController@getIndex'
]);

The word "slug" is no longer displayed as part of the URL. However, for some reason the slug's preceding '/' is still not visible, as though eaten by the slug in question! It now reads "http:[domain name]/posts**%7Bslug%7D**[article name]".

I'd really appreciate pointing in the right direction if anyone can lend a hand. Thank you.


Solution

  • Based on your comment, the way you're calling the action is incorrect. Try this view code:

    @if ($posts->count())
      @foreach ($posts as $post)
        <article>
          <h2><a href="{{ route('post-show', ['slug' => $post->slug]) }}">{{ $post->title }}</a></h2>  
          {{ Markdown::parse(Str::limit($post->body, 157)) }}
          <a href="{{ route('post-show', ['slug' => $post->slug]) }}">read more&hellip;</a>
        </article>
      @endforeach
    @endif
    

    I am not near a terminal to test this, but it should get you closer. The problems this code addresses are:

    1. To generate a URL using the route name, use route. Your code was using action.
    2. To pass a parameter and fill in the "{slug}", you pass an array as the second argument to route (and action for that matter). Your code was neither passing an array nor passing the value into the function.
    3. You were missing a } after the Markdown::parse, but that may have been a copy & paste error.