Laravel 레코드가 있는지 확인
나는 Laravel을 처음 사용합니다. 초보자 질문을 실례하지만 기록이 있는지 어떻게 알 수 있습니까?
$user = User::where('email', '=', Input::get('email'));
$user
기록이 있는지 확인하기 위해 여기서 무엇을 할 수 있습니까?
나중에 사용자와 작업 할 것인지 아니면 존재하는지 확인해야합니다.
존재하는 경우 사용자 오브젝트를 사용하려는 경우 :
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
그리고 당신이 확인하고 싶다면
if (User::where('email', '=', Input::get('email'))->count() > 0) {
// user found
}
아니면 더 좋은
if (User::where('email', '=', Input::get('email'))->exists()) {
// user found
}
가장 좋은 해결책 중 하나는 firstOrNew
또는 firstOrCreate
방법 을 사용하는 것입니다. 이 문서 에는 두 가지에 대한 자세한 내용이 있습니다.
if (User::where('email', Input::get('email'))->exists()) {
// exists
}
if($user->isEmpty()){
// has no records
}
Eloquent는 컬렉션을 사용합니다. 다음 링크를 참조하십시오 : https://laravel.com/docs/5.4/eloquent-collections
if (User::where('email', 'user@email.com')->first())
// It exists
else
// It does not exist
사용은 first()
하지 count()
만 존재 여부를 확인해야합니다.
first()
입니다 빨리 는 반면, 하나의 일치를 확인하기 때문에 count()
카운트 모든 경기.
라 라벨 5.6.26v
기본 키 (이메일 또는 아이디)를 통해 기존 레코드를 찾기 위해
$user = DB::table('users')->where('email',$email)->first();
그때
if(!$user){
//user is not found
}
if($user){
// user found
}
"DB 사용"을 포함하고 테이블 이름 사용자는 사용자와 같은 위의 쿼리를 사용하여 복수가됩니다.
요청 된 이메일이 사용자 테이블에 존재하는지 확인합니다.
if (User::where('email', $request->email)->exists()) {
//email exists in user table
}
컨트롤러에서
$this->validate($request, [
'email' => 'required|unique:user|email',
]);
보기에서-기존 메시지 표시
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
if ($u = User::where('email', '=', $value)->first())
{
// do something with $u
return 'exists';
} else {
return 'nope';
}
try / catch와 함께 작동합니다
-> get ()은 여전히 빈 배열을 반환합니다
기록이 있는지 없는지 간단하게 알 수 있습니다.
$user = User::where('email', '=', Input::get('email'))->get();
if(count($user) > 0)
{
echo "There is data";
}
else
echo "No data";
$user = User::where('email', request('email')->first();
return (count($user) > 0 ? 'Email Exist' : 'Email Not Exist');
laravel 유효성 검사를 사용할 수 있습니다.
그러나이 코드도 좋습니다.
$user = User::where('email', $request->input('email'))->count();
if($user > 0)
{
echo "There is data";
}
else
echo "No data";
표에 특정 이메일 주소가 있는지 확인합니다.
if (isset(User::where('email', Input::get('email'))->value('email')))
{
// Input::get('email') exist in the table
}
null
within if
문을 확인 하면 쿼리가 끝난 직후 Laravel에서 404가 반환되지 않습니다.
if ( User::find( $userId ) === null ) {
return "user does not exist";
}
else {
$user = User::find( $userId );
return $user;
}
사용자가 발견되면 이중 쿼리를 실행하는 것처럼 보이지만 다른 신뢰할 수있는 솔루션을 찾을 수없는 것 같습니다.
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
로 쓸 수 있습니다
if (User::where('email', '=', Input::get('email'))->first() === null) {
// user doesn't exist
}
This will return true or false without assigning a temporary variable if that is all you are using $user for in the original statement.
I think below way is the simplest way to achieving same :
$user = User::where('email', '=', $request->input('email'))->first();
if ($user) {
// user doesn't exist!
}
Created below method (for myself) to check if the given record id exists on Db table or not.
private function isModelRecordExist($model, $recordId)
{
if (!$recordId) return false;
$count = $model->where(['id' => $recordId])->count();
return $count ? true : false;
}
// To Test
$recordId = 5;
$status = $this->isModelRecordExist( (new MyTestModel()), $recordId);
Home It helps!
here is a link to something l think can assist https://laraveldaily.com/dont-check-record-exists-methods-orcreate-ornew/
$email = User::find($request->email);
If($email->count()>0)
<h1>Email exist, please make new email address</h1>
endif
In laravel eloquent, has default exists() method, refer followed example.
if(User::where('id', $user_id )->exists()){ // your code... }
Shortest working options:
// if you need to do something with the user
if ($user = User::whereEmail(Input::get('email'))->first()) {
// ...
}
// otherwise
$userExists = User::whereEmail(Input::get('email'))->exists();
this is simple code to check email is exist or not in database
$data = $request->all(); $user = DB::table('User')->pluck('email')->toArray(); if(in_array($user,$data['email'])) { echo 'existed email'; }
참고URL : https://stackoverflow.com/questions/27095090/laravel-checking-if-a-record-exists
'Programing' 카테고리의 다른 글
foreach와지도 사이에 차이가 있습니까? (0) | 2020.04.28 |
---|---|
우분투에서 postgresql을 완전히 제거하고 다시 설치하는 방법은 무엇입니까? (0) | 2020.04.28 |
ID와 클래스의 차이점은 무엇입니까? (0) | 2020.04.28 |
CSS를 사용하여 텍스트를 미러링 / 플립 할 수 있습니까? (0) | 2020.04.28 |
<% = f.submit %>에 CSS 클래스 추가 (0) | 2020.04.28 |