I have simple problem, I have to replace %20 and other crap from URL. At the moment it looks like this http://exmaple/profile/about/Eddies%20Plumbing
. As you can see it's profile link.
Yes I could add str_replace
values before every hyperlink, but I have like 10 of them and I think it's bad practice. Maybe there is better solution? What solution would you use? Thanks.
I am parsing the url tha i got in this way ->
The links are urlencoded. Use
urldecode($profileLink);
to decode them.That is not crap, that is a valid unicode representation of a space character. And it's encoded because it's one of the characters that are deemed unsafe by RFC1738:
So in order to have pretty URLs, you should avoid using reserved and unsafe characters which need encoding to be valid as part of a URL:
Instead replace spaces with dashes, which serve the same purpose visually while being a safe character, for example look at the Stack Overflow URL for this question. The URL below looks just fine and readable without spaces in it:
You can use Laravel's
str_slug
helper function to do the hard work for your:The
str_slug
does more that replace spaces with dashes, it replaces multiple spaces with a single dash and also strips all non-alphanumeric characters, so there's no reliable way to decode it.That being said, I wouldn't use that approach in the first place. There are two main ways I generally use to identify a database entry:
1. Via an ID
The route path definition would look like this in your case:
The code used to identify the user would look like this
User::find($id)
(theslug
parameter is not needed, it's just there to make the URL more readable, that's why I used the?
to make it optional).2. Via a slug
The route path definition would look like this in your case:
In this case I always store the slug as a column in the
users
table because it's a property relevant to that user. So the retrieval process is very easyUser::where('slug', $slug)
. Of course usingstr_slug
to generate a valid slug when saving the user to the database. I usually like this approach better because it has the added benefit of allowing the slug to be whatever you want (not really needing to be generated from the user name). This can also allow users to choose their custom URL, and can also help with search engine optimisation.In your view ...
and in controller using parsing your url as