I am new to Laravel. Please excuse the newbie question but how do I find if a record exists?
$user = User::where(\'em
if($user->isEmpty()){
// has no records
}
Eloquent uses collections. See the following link: https://laravel.com/docs/5.4/eloquent-collections
if (User::where('email', 'user@email.com')->first()) {
// It exists
} else {
// It does not exist
}
Use first()
, not count()
if you only need to check for existence.
first()
is faster because it checks for a single match whereas count()
counts all matches.
Laravel 5.6.26v
to find the existing record through primary key ( email or id )
$user = DB::table('users')->where('email',$email)->first();
then
if(!$user){
//user is not found
}
if($user){
// user found
}
include " use DB " and table name user become plural using the above query like user to users
It's simple to get to know if there are any records or not
$user = User::where('email', '=', Input::get('email'))->get();
if(count($user) > 0)
{
echo "There is data";
}
else
echo "No data";
It depends if you want to work with the user afterwards or only check if one exists.
If you want to use the user object if it exists:
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
And if you only want to check
if (User::where('email', '=', Input::get('email'))->count() > 0) {
// user found
}
Or even nicer
if (User::where('email', '=', Input::get('email'))->exists()) {
// user found
}
This will check if requested email exist in the user table:
if (User::where('email', $request->email)->exists()) {
//email exists in user table
}