Laravel 5 mewebstudio/captcha not working - php

I have got problem with Laravel 5 mewebstudio/captcha.
I install it and on my page is captcha image
echo captcha_img()
echo Form::text('captcha','',["class"=>"form-control","placeholder"=>trans('page.captcha')]);
This works fine.
But the problem is with the validation, after the validation form I get a message about incorrect captcha.
My validation code:
if (Request::isMethod('post')){
//$data = Input::except(array('_token'));
$data = Input::all();
$rule = array(
'name' => 'required',
'firstname' => 'required',
'bdate' => 'required',
'email' => 'required|email',
'password' => 'required|min:6|same:password_repeat',
'password_repeat' => 'required|min:6',
'captcha' => 'required|captcha'
);
$validator = Validator::make($data, $rule);
if ($validator->fails()) {
$errors = $validator->messages();
}
}
I think captcha session is not working because after dump session I don't have captcha key which should be put in session (I found in Captcha.php )
$this->session->put('captcha', [
'sensitive' => $this->sensitive,
'key' => $this->hasher->make($this->sensitive ? $bag : $this->str->lower($bag))
]);

In Laravel 5.2 you need to change line 29 in CaptchaServiceProvider to
$this->app['router']->group(['middleware' => 'web'], function () {
$this->app['router']->get('captcha/{config?}', '\Mews\Captcha\CaptchaController#getCaptcha');
});

I solved this problem.
In Laravel 5.2 you need to change line 26 in CaptchaServiceProvider to
$this->app['router']->get('captcha/{config?}', \Mews\Captcha\CaptchaController#getCaptcha')->middleware('web');

Related

How to update a user only when value has not changed in the database and also avoid using other people's email

So, I have controller method which validates user and updates their information.
public function updateBasicInfo(Request $request)
{
$basic_info = Validator::make($request->all(), [
'fullname' => 'required|min:2|max:255',
'phone_number' => 'required|numeric|min:10',
'email' => 'required',
'country' => 'required',
'address' => 'required',
], [
'phone_number.min' => "The phone number must be at least 10 digits",
]);
if($basic_info->fails())
{
return response()->json([
'errors'=> $basic_info->errors()->all(),
]);
}
else
{
$basic_info = $basic_info->validated();
$user = request()->session()->get('id');
$currentUser = User::firstWhere('username', $user->username);
$currentUser->name = $basic_info['fullname'];
$currentUser->phone_number = $basic_info['phone_number'];
$currentUser->email = $basic_info['email'];
$currentUser->save();
UserDetail::firstWhere(['username' => $user->username])->update([
'address'=>$basic_info['address'],
'country' => $basic_info['country'],
]);
$current_user = $currentUser;
Mail::to($current_user->email)->send(new ProfileMail($user));
return response()->json(['success'=> 'Profile Updated Sucessfully']);
}
}
I want to update user but I don't want two users to have the same email and I also want the user email to change only if it's value has been changed in the database.
Check to make sure that only the user has that email in the whole table and update it to prevent double email records
Please, how do I do this?
I have tried calling the isDirty() method,nothing seems to work
You can use the unique validation rule for email with ignore to make sure that it doesn't receive an error if the new email is the same as the last email. (Unique validation only in comparison with other users). Check out this link.
$basic_info = Validator::make($request->all(), [
'fullname' => 'required|min:2|max:255',
'phone_number' => 'required|numeric|min:10',
'email' => 'required|unique:users,email,'.request()->session()->get('id'),
'country' => 'required',
'address' => 'required',
], [
'phone_number.min' => "The phone number must be at least 10 digits",
]);
The isDirty() method is to check if you set a value to any of the properties of instance. And it checks the change after it occured.isDirty()

Concaternate Array value with Ternary Operator result

I'm using PHP 7 and Laravel 6. I got errors when I made a user request rule and used it in user controller. The request rule I made is to be reusable in create and update function, so if i pass the id of user, it will validate the unique of user except that id. But if not, it will search all the ids and validate if it's unique. I follow BaM solution, here: https://stackoverflow.com/a/24205849
This my UserRequest.php:
public static function rules ($id=0, $merge=[]) {
return array_merge(
[
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users' . ($id ? ",$id" : ''),
'phone_number' => 'required|string|min:9|max:10|unique:users' . ($id ? ",$id" : ''),
'user_img' => 'required|mimes:jpeg,jpg,png,gif|max:10000',
],
$merge);
}
This is my UserController:
public function store(Request $request)
{
$extend_rules = [
'pass' => 'required|string|min:8',
];
$validator = Validator::make($request->all(), UserRequest::rules($extend_rules));
if ($validator->fails())
{
return redirect()->back();
}
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->pass),
'phone_number' => $request->phone_number,
'user_img' => $request->user_image->store('user_img'),
]);
$user->save();
Session::flash('message', 'Your account is successfully created !');
Session::flash('alert-class', 'alert alert-success');
return redirect()->route('users.index');
}
And I got this errors:
ErrorException: Array to string conversion
I tried to search for solutions but couldn't seem to find anything much my case.
If anyone know, please help me!
That's because you're just passing an array while the method accept two different type of parameter
$validator = Validator::make($request->all(), UserRequest::rules(0, $extend_rules)); // <-- you need to either pass 1 or 0 for the id and then $extended rules
// here is your method signature
public static function rules ($id=0, $merge=[]) {

Call to a member function fails() on array on laravel

Iam just trying to validate some POST datas.
Route::post('/', function(){
$data = ['url' => request('url')];
$validation = Validator::make($data, ['url' => 'required|url'])->validate();
if($validation->fails())
{
$dd('failed');
}
I don't understand why It doesn't work, can you help me please ?
The error you're getting is due to the return type of ->validate(). This will return an array, so $validation will be an array instead of a Validator instance, and you can't call ->fails() on an array. To solve this, simply omit ->validate():
$validation = Validator::make($data, ['url' => 'required|url']);
if($validation->fails()){
dd("Failed");
}
Sidenote; watch your syntax. $dd() is not a valid call.
You may use the validate method provided by the Illuminate\Http\Request object directly as follow
$request->validate([
'title' => 'required|unique:posts|max:255',
'author.name' => 'required',
'author.description' => 'required',
]);
//if fails code after this line will not be executed
This validation will auto redirected to back.This was default validation by laravel. If it not fails,it will continue with executing.
Manually
Now you can implement manually and redirect as your requirment.
use Validator;
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
//checks your validation and redirect as you want
if ($validator->fails()) {
return redirect('where/ever/you/want')
->withErrors($validator)
->withInput();
}
Again you can default redirection,by calling validate() method
Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
])->validate();
If you call validate method it will redirect as default laravel.
dd() is a method,short version of die and dump
Useful link:
https://github.com/laravel/framework/blob/5.7/src/Illuminate/Validation/Validator.php#L312

Wrong Laravel validation messasges

I get the wrong error messages. My purpose is following :
1. checking username / pw combination, and if it doesn't match, "wrong username/pw combination" error through validator.
2. captcha (mews) is troubling me. Even user enters true captcha chars (no case-sensitive by config) I get the error message.
Here is my validator :
FYI: i have a table "user" instead of users, and i can use it nicely in other controllers.
protected function loginValidator()
{
$message = array(
'exists:user,username' => 'Wrong username/pass combination',
'exists' => 'Wrong :attribute.',
'required' => ':attribute cannot be empty',
'captcha' => 'Wrong captcha'
);
return Validator::make(Input::all(),[
'usernameInput' => 'required|exists:user,username',
'passwordInput' => 'required',
'captchaInput' => 'captcha|required'
], $message);
}
Even if username/pass combination is true, i get wrong captcha message.
Thanks in advance.
protected function loginValidator()
{
$validator = Validator::make(
array(
'name' => 'Dayle',
'password' => 'lamepassword',
'email' => 'email#example.com'
),
array(
'name' => 'required',
'password' => 'required|min:8',
'email' => 'required|email|unique:users'
)
);
if ($validator->fails())
{
// The given data did not pass validation
$data['messages'] = $validator->messages()->all();
}
else
{
//complete validation
}
return View::make('home.login', $data);
}

Laravel MethodNotAllowedHttpException, but my methods match

I have a registration form that I'm creating using the blade templating like so:
{{ Form::open(array('url'=>'registerUser', 'method'=>'POST', 'class'=>'loginForm SignUp')) }}
In routes.php, I have the following route:
Route::post('registerUser', 'UsersController#doRegister');
But when I submit the form, I get a MethodNotAllowedHttpException. Pretty much every other question I've found online about this was a case of the form having the GET method while the route had POST, but mine match, so I'm pretty confused.
Edit: Here's my full routes file:
Route::get('', 'UsersController#showLogin');
Route::get('login', 'UsersController#showLogin');
Route::post('doLogin', 'UsersController#doLogin');
Route::get('signUp', 'UsersController#showSignUp');
Route::post('authenticateCode', 'UsersController#authenticateCode');
Route::post('requestCode', 'UsersController#requestCode');
Route::get('showRegister', 'UsersController#showRegister');
Route::post('registerUser', 'UsersController#doRegister');
Route::get('dashboard', 'DashboardController#showDashboard');
Here's the controller function:
public function doRegister() {
$rules = array(
'fname' => 'required|alpha|min:2',
'lname' => 'required|alpha|min:2',
'email' => 'required|email|unique:users',
'phone' => 'required|alpha_num|min:7',
'company' => 'required|alpha_spaces|min:2',
'password' => 'required|alpha_num|between:6,12|confirmed', // these password rules need to be improved
'password_confirmation' => 'required|alpha_num|between:6,12'
);
$validator = Validator::make(Input::all(), $rules);
if($validator->passes()) {
$user = User::create(array(
'fname' => Input::get('fname'),
'lname' => Input::get('lname'),
'email' => Input::get('email'),
'password' => Hash::make(Input::get('password')),
'phone' => Input::get('phone'),
'company' => Input::get('company')
));
// Update the invite key that was passed to the register page
// with this new user's ID.
$key = InviteKey::find(Input::get('key'));
$key->user_id = $user->id;
$key->save();
return Redirect::to('login')->with('message', 'Thank you for registering!');
} else {
return Redirect::to('register')
->with('message', 'The following errors occurred')
->withErrors($validator)
->withInput(Input::except('password'));
}
}

Categories