Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a complete clean URL

Tags:

sql

php

.htaccess

I'm trying to figure out to get a complete clean url for my blog. Right now I have a decent url that looks like this:

http://example.com/post/44/post-name

Here "44" is the Post ID which I use to get the correct post from the database.

But I have seen wordpress blog having url's like this:

http://example.com/post-name

How can this be achieved? as I need the post ID / $_GET['id'] to be able to get the post.

like image 320
Troels Johannesen Avatar asked Jan 18 '26 22:01

Troels Johannesen


1 Answers

You don't necessarily need the id to retrieve the Post. You only need an indexed attribute with unique values.

To achieve this, your Post model needs to have a "slug" attribute. That slug attribute can be based on any other attribute or combination of attributes you choose, but it's usually based on a "name" or "title" attribute.

So to make all this work, when you create a new Post, you need to create a slug from the name/title and store that in the DB, along with the other Post model data. In your controller action you will then retrieve the /slug from the URL and query the db Post data for a Post with the same slug.

You'll also need to figure out to handle duplicate slugs as they need to be unique. Perhaps something like this would work: /slug-2

like image 80
Michael Gregoire Avatar answered Jan 21 '26 10:01

Michael Gregoire