I am using Laravel 5.2. I am looking querying usernames with eloquent in order to create a unique profile page. The issue I am having is the usernames are returning with white space e.g. John Doe I need it to return with no white space like johndoe or JohnDoe. Thanks.
public function show($username)
{
try
{
$user = str_replace(' ', '', User::wherename($username)->firstOrFail());
dd($user);
}
catch(ModelNotFoundException $e)
{
return redirect()->action('HomeController@index');
}
}
This can help -
str_replace(" ", "", "John Doe");
Or if there is multiple spaces (continuous) -
preg_replace('/\s+/', '', "John Doe");
Update
After discussion, I think you need to use slugs:
$user = User::findBySlug($username);
$name = $user->name;
In this case, you'll have two columns in your table: name ('John Doe', for example) and slug ('JohnDoe' or 'johndoe' or 'John_Doe' etc).
Original answer
If you want to remove spaces from the beginning and the end of a string, try to trim them:
$userOriginal = User::where('name', $username)->first();
$user = trim($userOriginal->name);
To remove all spaces, use this:
$user= str_replace(' ', '', User::where('name', $username-)->first()->name);
$user = User::wherename($username)->first();
if($user){
$user_name = preg_replace('/\s+/', '', $user->name); //or other column that you need to clean
return dd($user_name);
}
return 'No user found!';
You can create a function on your User
model that returns name
without any spaces. Like so:
public function getNameWithoutSpaces() {
return preg_replace('/\s+/', '', $this->name);
}
This way you can get the name without spaces wherever needed without having to use the str_replace
function all the time.
$user = User::wherename($username)->first()
$UserName = preg_replace('/\s+/', '', $user->name);
print_r($UserName );die;
You can define getter on your user model
public function getNameAttribute() {
return preg_replace('/\s+/', '', $this->attribute['name'])
}
After that when you try get $user->name
, it always be without spaces.