2017-02-23 289 views
-5

我正在使用Laravel 5.2.45Laravel檢查用戶是否存在

我正嘗試爲我的應用程序創建新用戶。 在創建用戶之前,我需要檢查是否有用戶具有相同的姓名和生日。 我該怎麼做laravel?

+0

由d查看數據庫查詢以查看這些值是否在數據庫中。請參閱[查詢構建器文檔](https://laravel.com/docs/5.2/queries)。你的問題很基本,很可能會被封閉,因爲你沒有任何代碼表明你已經試圖自己做這件事。 –

+0

laravel提供了例如'unique'來檢查數據庫中是否存在一些數據。但我不想找一個條目。 3個條目必須匹配以提供錯誤。我知道我可以做一個數據庫查詢,並檢查是否已經有一個現有的用戶,但認爲有更好的方法來做laravel – hatemjapo

回答

5

用戶使用相同的名字,姓氏和生日

$duplicate_user = \DB::table('users') 
    ->where('name', 'LIKE', $new_name) 
    ->where('surname', 'LIKE', $new_surname) 
    ->where('birthday', '=', $new_birthday) 
    ->first(); 

if($duplicate_user) { 
    return response('This user already exists', 422); 
} 
0

由於Laravel驗證Docs

獨特:表,列,除非,idColumn

Validator::extend('and_unique', function($attribute, $value, $parameters, $validator) { 
$result = DB::table($parameters[0])->where(function($query) use ($attribute, $value, $parameters) { 
    $query->where($attribute, '=', $value) // where name = value 
     ->orWhere($parameters[1]), '=', $value); // where surname = value 
     ->orWhere($parameters[2]), '=', $value); // where birthday = value 
})->first(); 

return $result ? false : true; 
}); 

'name' => 'required|and_unique:users,surname,birthday' 
+0

這是行不通的。如果其中一個名字,姓氏或生日被採取,這將給一個錯誤。 – hatemjapo

0
$siteUser = new SiteUser; 

foreach (['birth_date', 'first_name', 'last_name'] as $key) { 
$siteUser->$key = $request->$key; 
} 
+1

你可以在你的答案中添加一些細節嗎?爲什麼OP應該使用這段代碼? – Jer