How to check if email exists in laravel Login - laravel

I want to check if the log in details i.e the email is in the database and echo error like "Email Does Not Exists" in the front-end.
$this->validate($request,[
'email' => 'required',
'password' => 'required',
]);
Above is my current validation.
How do i check if the email exists before logging them in.

$this->validate($request,[
'email' => 'required|unique:users,email', // users is table name,email is column
'password' => 'required',
]);
in blade you can do as follows
#error('email')
<div class="alert alert-danger">{{ $message }}</div>
#enderror

You may use custom validation. Here is an example:
$this->validate($request,[
'email' => ['required', function ($attribute, $value, $fail) {
$email = User::where('email', $value)->first();
if ($email == null) {
$fail($attribute.' does not exist.');
}
},],
'password' => 'required',
]);

Related

Get a session element in the view with Laravel

I'm trying to implement Google Recaptcha in my user registration form.
Controller
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'surname' => ['required', 'string', 'max:255'],
'nickname' => ['required', 'string', 'max:255', 'min:5', 'unique:users'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
'g-recaptcha-response' => function ($attribute, $value, $fail) {
$secretKey = config('services.recaptcha.secret');
$response = $value;
$userIP = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$response&remoteip=$userIP";
$response = file_get_contents($url);
$response = json_decode($response);
if (!$response->success) {
Session::flash('errorCaptcha', 'Per favore controlla il reCaptcha!');
$fail($attribute . 'Google reCaptcha fallito!');
}
}
]);
}
Instead, the code in the view should show an error message if the user does not confirm the Recaptcha.
Blade
#if(Session::has('errorCaptcha'))
<span class="invalid-feedback" role="alert">
<strong>{{ Session::get('errorCaptcha') }}</strong>
</span>
#endif
In the controller I run:
dd(session::get('errorCaptcha'))
I get the value in the controller but not in the view. Can anyone help me, please?

laravel link a registration form to database field

I am using teams in laravel and want to add a company name field to my registration form instead of it running the standard:
'name' => explode(' ', $user->name, 2)[0]."'s Team",
I am still wanting to keep the field called name but use the input fields data, I have tried changing the method to:
protected function createTeam(User $user)
{
$user->ownedTeams()->save(Team::forceCreate([
'user_id' => $user->id,
'name' => $user['company_name'],
'personal_team' => true,
]));
}
but it doesn't work as intended. My register.blade.php is:
<div>
<x-jet-label value="{{ __('Company Name') }}" />
<x-jet-input class="block mt-1 w-full" type="text" name="company_name" :value="old('company_name')" autofocus autocomplete="company_name" />
</div>
my migration is unchanged as I am wanting to force the name through my form instead of it generating it based on the user input of name.
The complete CreateNewUser method is:
public function create(array $input)
{
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => $this->passwordRules(),
])->validate();
return DB::transaction(function () use ($input) {
return tap(User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
]), function (User $user) {
$this->createTeam($user);
});
});
}
/**
* Create a personal team for the user.
*
* #param \App\Models\User $user
* #return void
*/
protected function createTeam(User $user)
{
$user->ownedTeams()->save(Team::forceCreate([
'user_id' => $user->id,
'name' => $user['company_name'],
'personal_team' => true,
]));
}
}

laravel select box value not adding to database

so am trying to send the value of a select box to database to calculate admin roles but it doesn't receive the value here is my view
<div class="form-group row">
<label for="exampleFormControlSelect1" class="col-md-4 col-form-label text-md-right">Role</label>
<div class="col-md-6">
<select class="form-control" id="exampleFormControlSelect1" name="role">
<option value="1">Super Admin</option>
<option value="2">Admin</option>
<option value="3">Doctor</option>
<option value="4">Sales</option>
</select>
</div>
</div>
and this is my controller its for adding new admins to the database (not users with admin roles)
public function showRegistrationForm()
{
return view('auth.admin-register');
}
public function register(Request $request)
{
// Validate form data
$this->validate($request,
[
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:admins'],
'password' => ['required', 'string', 'min:8'],
'role' => ['required']
]
);
dd($request->role);
// Create admin user
try {
$admin = Admin::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'role' => $request->role
]);
return redirect()->route('admin.dashboard');
} catch (\Exception $e) {
return redirect()->back()->withInput($request->only('name', 'email'));
}
}
the dd($request->role) works and return the nvalue of the but the problem is with the
try {
$admin = Admin::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'role' => $request->role
]);
In model you can define protected columns then all the other column will be auto fillable
or you can define fillable columns in model
The problem was that I didn't set the role in fillable in admin model

Solving Method Not Allowed Http Exception in Laravel 5.2

I want some values in my table editable, so I created this simple custom form. But this will throw error of method not allowed http exception.Any help?
<form action="{{ url('/idx-test/update-this-student/'. $student->id)}}" class="" method="POST">//changing this to put, patch does not solve the error
Route
Route::post('/idx-test/update-this-student/{id}', 'StudentController#updateThisStudent'); //again changing this to patch,or put does not help
Controller
public function updateThisStudent(StudentRequest $request, $id)
{
$student = Student::findOrFail($id);
$student->update($request->all());
// return redirect('city');
echo "updated";
}
StudentRequest
public function rules()
{
return [
'firstname' => 'required|alpha|min:2|max:10',
'lastname' => 'required|alpha|min:2|max:10',
'bday' => 'required|date',
'address' => 'required|min:10',
'zip' => 'required|min:4|max:10',
'phone' => 'required|digits:7',
'mobile' => 'required|digits:11',
'email' => 'required|email',
'city_id' => 'required',
'yearlevel_id' => 'required',
'section_id' => 'required',
];
}
By adding this small piece of code
<input type="hidden" name="_method" value="PATCH">
My problem solve

Laravel Spark - Adding additional fields to registration form, but when empty no errors are returned

I'm building my first app with Laravel 5.2 & Laravel Spark. The front end is built using Vue.js I believe and despite adding the following to register-common-form.blade.php:
<!-- Username -->
<div class="form-group" :class="{'has-error': registerForm.errors.has('username')}">
<label class="col-md-4 control-label">Username</label>
<div class="col-md-6">
<input type="name" class="form-control" name="username" v-model="registerForm.username" autofocus>
<span class="help-block" v-show="registerForm.errors.has('username')">
#{{ registerForm.errors.get('username') }}
</span>
</div>
</div>
I can't actually see a way to fully register that extra field so that it is picked up for error handling. I've got it so that the UserRepository handles the field and inserts it, but just can't get the front end errors to show properly.
Is anyone able to help with this at all?
Okay I finally stumbled across it :D
In Laravel\Spark\Interactions\Auth\CreateUser.php there is a $rules method like so:
public function rules($request)
{
return [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
'vat_id' => 'max:50|vat_id',
'terms' => 'required|accepted',
];
}
All I have done is add my username field, and it works brilliantly!
public function rules($request)
{
return [
'name' => 'required|max:255',
'username' => 'required|unique:users',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
'vat_id' => 'max:50|vat_id',
'terms' => 'required|accepted',
];
}
Above answer is just for validation rules you also need to navigate to spark\src\Repositories\UserRepository.php and add 'username' => $data['username'], to the create() method like this:
public function create(array $data)
{
$user = Spark::user();
$user->forceFill([
'name' => $data['name'],
'username' => $data['username'], // ADDED THIS
'email' => $data['email'],
'password' => bcrypt($data['password']),
'confirmation_code' => str_random(30),
'last_read_announcements_at' => Carbon::now(),
'trial_ends_at' => Carbon::now()->addDays(Spark::trialDays()),
])->save();
return $user;
}

Resources