Search code examples
phplaravelurlpermalinksslug

Laravel custom permalink


I am trying to change the url of my article page so instead of showing the article id I'd like to show the article title.

Currently the URL is as follows; https://www.example.com/posts/post/32 Where 32 is just a random article id.

Instead I like it to display as follows; https://www.example.com/posts/post/my-amazing-article

Now I have looked in the laravel documentation and different posts on stackoverflow and tried a bunch of stuff but I'm obviously making a mistake somewhere cus nothing seems to work so im pretty much back where I started.

Blade

<a href="{{ route('post', $a->id) }}" class="feature-box-01 media" id="smallbox"></a>          

Route

Route::get('/posts/post/{id}', [App\Http\Controllers\WelcomeController::class, 'post'])->name('post');

Controller

public function post(request $request){
    $id = $request->id;
    $article = Tinymce::find($id);

    return view('/post')->with('articles, $articles');
}

Now the articles, which are saved in Tinymce, are actually created on a different controller on subdomain.

public function tinymce(Request $request)
    {
        
        if(request()->ajax())
        {   
            if($request->article_id == null)
            {
                $tinymce = new Tinymce;
                
                
            }else{

                $tinymce = Tinymce::find($request->article_id);
            }
            
            $tinymce->description = $request->description;
            $tinymce->content = $request->myContent;
            $tinymce->title = $request->title;
            $tinymce->author = $request->author;
            $tinymce->publish = $request->publish;
            $title = $tinymce->title;
            $slug = Str::slug($title, "-");
            $tinymce->slug = $slug;            
            $tinymce->save();

            
            return $tinymce->id;
        }
        
    }

As you can see I've turned the title into a slug as I read somewhere that's the way to go to use custom url but I didn't get very far with it.

Any help would be greatly appreciated, thank you.


Solution

  • Explanation:

    First, As you said you stored slug into your database. so, that's good.

    From Controller to View, you can get that slug into post object.

    Blade View : (you have to pass slug in route url)

    <a href="{{ route('post', $a->slug) }}" class="feature-box-01 media" id="smallbox"></a>          
    

    Route : (make id to slug)

    Route::get('/posts/post/{slug}', [App\Http\Controllers\WelcomeController::class, 'post'])->name('post');
    

    Controller : (now you can get slug from the second parameter)

    public function post(request $request, $slug = ''){
        $article = Tinymce::where('slug', $slug)->first();
    
        return view('/post', compact('article'));
    }
    

    Now, you can use access custom URLs using slug.

    I Hope, it helps you. @assiemp