Skip to content

Instantly share code, notes, and snippets.

@mercuryseries
Created November 29, 2016 18:19
Show Gist options
  • Save mercuryseries/5393247cd3626fee546be579ef0dbb22 to your computer and use it in GitHub Desktop.
Save mercuryseries/5393247cd3626fee546be579ef0dbb22 to your computer and use it in GitHub Desktop.
EditAccountRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
class EditAccountRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return Auth::check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|min:4|max:255',
'email' => [
'required',
'email',
'max:255',
Rule::unique('users')->ignore(Auth::id()),
],
'password' => 'min:6|confirmed',
'password_confirmation' => 'required_with:password',
'username' => 'min:3|alpha_dash',
'notify_using_email' => 'boolean',
'allows_marketing_email' => 'boolean',
];
}
/**
* Get the validator instance for the request and
* add attach callbacks to be run after validation
* is completed.
*
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function getValidatorInstance()
{
return parent::getValidatorInstance()->after(function($validator){
$this->after($validator);
});
}
/**
* Attach callbacks to be run after validation is completed.
*
* @param \Illuminate\Contracts\Validation\Validator $validator
* @return void
*/
protected function after($validator)
{
if($this->currentPasswordIsRequired() && $this->currentPasswordIsNotProvided()) {
$validator->errors()->add('current_password', 'Votre mot de passe actuel est requis si vous souhaitez changer votre adresse électronique ou votre mot de passe.');
}
if($this->currentPasswordIsRequired() && !$this->currentPasswordProvidedIsValid()) {
$validator->errors()->add('current_password', 'Le mot de passe actuel fourni est invalide.');
}
}
private function currentPasswordIsRequired()
{
return $this->userWantsToChangeEmail() || $this->userWantsToChangePassword();
}
private function currentPasswordIsNotProvided()
{
return empty($this->current_password);
}
private function userWantsToChangeEmail()
{
return $this->user()->email !== $this->email;
}
private function userWantsToChangePassword()
{
return !empty($this->password);
}
private function currentPasswordProvidedIsValid()
{
return Hash::check($this->current_password, $this->user()->password);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment