返回没有空格的数据

时间:2016-04-25 12:29:03

标签: php laravel eloquent

我使用的是Laravel 5.2。我正在寻找用eloquent查询用户名以创建一个独特的个人资料页面。我遇到的问题是用户名返回白色空格,例如John Doe我需要它返回,没有像johndoe或John Doe这样的空白区域。感谢。

public function show($username)
{
    try
    {
        $user = str_replace(' ', '', User::wherename($username)->firstOrFail());
        dd($user);

    }
    catch(ModelNotFoundException $e)
    {
        return redirect()->action('HomeController@index');
    }
}

6 个答案:

答案 0 :(得分:1)

您可以在User模型上创建一个函数,该函数返回name,不带任何空格。像这样:

public function getNameWithoutSpaces() {
    return preg_replace('/\s+/', '', $this->name);
}

这样,您可以在任何需要的地方获取没有空格的名称,而无需始终使用str_replace函数。

答案 1 :(得分:0)

这可以提供帮助 -

str_replace(" ", "", "John Doe");

或者如果有多个空格(连续) -

preg_replace('/\s+/', '', "John Doe");

答案 2 :(得分:0)

<强>更新

经过讨论,我认为您需要使用slugs

$user = User::findBySlug($username);
$name = $user->name;

在这种情况下,您的表格中会有两列:名称(例如,&#39; John Doe&#39;)和 slug (&#39; JohnDoe&#39;或&#39; johndoe&#39;或&#39; John_Doe&#39;等)。

原始回答

如果要从字符串的开头和结尾删除空格,请尝试trim

$userOriginal = User::where('name', $username)->first();
$user = trim($userOriginal->name);

要删除所有空格,请使用:

$user= str_replace(' ', '', User::where('name', $username-)->first()->name);

答案 3 :(得分:0)

$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!';

答案 4 :(得分:0)

$user = User::wherename($username)->first()

$UserName = preg_replace('/\s+/', '', $user->name);
print_r($UserName );die;

答案 5 :(得分:0)

您可以在用户模型上定义getter

$user->name

在您尝试获取SELECT ac.id, ac.name, ac.link, ac.type, ac.country, co.name AS countryName, ac.state, st.statename, ac.cityid AS cityId, ci.name AS cityName, ac.addr, ac.featuredimage, ac.amenities, ac.starrating, ac.bookings_received, ro.roomprice, SUM(ro.numberofrooms) AS totalRooms, SUM(numberofroomsbooked) AS bookedRooms FROM accomodations ac JOIN bookings b ON ac.id = b.hotelid JOIN countries co ON ac.country = co.id JOIN states st ON ac.state = st.id JOIN city ci ON ci.id = ac.cityid JOIN room ro ON ac.id = ro.hotel WHERE ac.active = 1 AND ac.delete = 0 AND reservationto >= '2016-07-07' AND reservationfrom <= '2016-07-09' GROUP BY ac.id; 之后,它始终没有空格。