I'm trying to check if the email is already exist my database on my subscribes table.
Form
{!! Form::open(array('url' => '/subscribe', 'class' => 'subscribe-form', 'role' =>'form')) !!}
<div class="form-group col-lg-7 col-md-8 col-sm-8 col-lg-offset-1">
<label class="sr-only" for="mce-EMAIL">Email address</label>
<input type="email" name="subscribe_email" class="form-control" id="mce-EMAIL" placeholder="Enter email" required>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;"><input type="text" name="b_168a366a98d3248fbc35c0b67_73d49e0d23" value=""></div>
</div>
<div class="form-group col-lg-3 col-md-4 col-sm-4"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="btn btn-primary btn-block"></div>
{!! Form::close() !!}
Controller
public function postSubscribe() {
// Validation
$validator = Validator::make( Input::only('subscribe_email'),
array(
'email' =>'unique:subscribes',
)
);
if ($validator->fails()) {
return Redirect::to('/#footer')
->with('subscribe_error','This email is already subscribed to us.')
->withErrors($validator)->withInput();
}else{
dd("HERE");
$subscribe = new Subscribe;
$subscribe->email = Input::get('subscribe_email');
$subscribe->save();
return Redirect::to('/thank-you');
}
}
Debuging Steps
I tried inputting email that I know already exist in my db.
I want to my validation to fail, and redirect me back to my /#footer (homepage).
I try printing dd("HERE"); if my vaildation not fail.
BUT I keep getting HERE to print which mean my validation is not failing.
Why is that happening ? I'm completely blank out now.
Can someone please point out what I missed ?
I know I am very close.
Thanks.
Your db field name is email not subscribe_email, your input param name however is. Laravel defaults to the fieldname given with the input, so in your case subscribe_email
Try this:
array(
'subscribe_email' => 'required|email|unique:subscribes,email',
)
This uses the db fieldname email, like you have, but the validation is on the field subscribe_email.
try specifying the column name of email in subscribes table
$rules = array(
'email' => 'email|unique:subscribes,email'
);
It looks like the reason this is not working is because you are trying to match the subscribe_email field against validation for a email field, no match is being made. To fix you need to do this:
$validator = Validator::make( Input::only('subscribe_email'),
array(
'subscribe_email' =>'email|unique:subscribes,email',
)
);
//put this in your controller
if (User::where('email', '=', Input::get('email'))->exists()) {
return back()->withErrors([
'message' => 'Email is already taken'
]);
//then go up and include
use Illuminate\Support\Facades\Input;
Related
I have a Controller method like this:
use Validator;
public function insert(Request $request)
{
$data = Validator::make(request()->all(),[
'title' => 'required',
'name' => 'required|alpha_num',
'activation' => 'nullable',
'cachable' => 'nullable'
])->validated();
$wallet = new Wallet();
$wallet->title = $data['title'];
$wallet->name = $data['name'];
if (!empty($data['activation'])) {
$wallet->is_active = 1;
} else {
$wallet->is_active = 0;
}
if (!empty($data['cachable'])) {
$wallet->is_cachable = 1;
} else {
$wallet->is_cachable = 0;
}
$wallet->save();
return redirect(url('admin/wallets/index'));
}
And then I tried showing errors like this:
#error("name")
<div class="alert alert-danger">{{$message}}</div>
#enderror
But the problem is, it does not print any error when I fill the form incorrectly.
So how to fix this and show errors properly?
Here is the form itself, however it submits data to the DB correctly:
<form action="{{ route('insertWallet') }}" method="POST" enctype="multipart/form-data">
#csrf
<label for="title" class="control-label">Title</label>
<br>
<input type="text" id="title-shop" name="title" class="form-control" value="" autofocus>
#error("title")
<div class="alert alert-danger">{{$message}}</div>
#enderror
<label for="title" class="control-label">Name</label>
<br>
<input type="text" id="title-shop" name="name" class="form-control" value="" autofocus>
#error("name")
<div class="alert alert-danger">{{$message}}</div>
#enderror
<input class="form-check-input" type="checkbox" name="cachable" value="cashable" id="cacheStatus">
<label class="form-check-label" for="cacheStatus">
With Cash
</label>
<input class="form-check-input" type="checkbox" name="activaton" value="active" id="activationStatus">
<label class="form-check-label" for="activationStatus">
Be Active
</label>
<button class="btn btn-success">Submit</button>
</form>
check the official documentation here
add the following code
if($data->fails()){
return redirect(url('admin/wallets/index'))->withErrors($data)->withInput();
}
And after that save your data in your database
You are not returning any errors, you are just redirecting back to the view without any data.
Your fix would be to have your validator as this:
$data = Validator::validate(request()->all(),[
'title' => 'required',
'name' => 'required|alpha_num',
'activation' => 'nullable',
'cachable' => 'nullable'
]);
See that I have changed Validator::make to Validator::validate. As the documentation states:
If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user.
If validation fails during a traditional HTTP request, a redirect response to the previous URL will be generated. If the incoming request is an XHR request, a JSON response containing the validation error messages will be returned.
So, if your validation passes, it will save all the validated data into $data, as you did with ->validated() (but you don't have to write it here), and if it fails, it will automatically throw an Exception, in this case ValidationException, so Laravel will automatically handle it and redirect back with to the same URL and with the errors. So it now should work...
This is the Validator::validate source code and this is the validate source code for the validator validate method.
I'm currently trying to make change password functionality to my user profile all my inputs are submitted to the controller, but I think there might be something wrong with my function logic maybe?
Tried dumping request on function and dump was successfully returned. But when wrapping a validation variable around a validation process, the dump was not returned. The request redirects back to the profile page with form data.
Controller
public function updatePassword(Request $request)
{
$this->validate($request, [
'old_password' => 'required',
'new_password' => 'required|confirmed',
'password_confirm' => 'required'
]);
$user = User::find(Auth::id());
if (!Hash::check($request->current, $user->password)) {
return response()->json(['errors' =>
['current' => ['Current password does not match']]], 422);
}
$user->password = Hash::make($request->password);
$user->save();
return $user;
}
View
<form method="POST" action="{{ route('update-password') }}">
#csrf
#method('PUT')
<div class="form-group row">
<label for="old_password" class="col-md-2 col-form-label">{{ __('Current password') }}</label>
<div class="col-md-6">
<input id="old_password" name="old_password" type="password" class="form-control" required autofocus>
</div>
</div>
<div class="form-group row">
<label for="new_password" class="col-md-2 col-form-label">{{ __('New password') }}</label>
<div class="col-md-6">
<input id="new_password" name="new_password" type="password" class="form-control" required autofocus>
</div>
</div>
<div class="form-group row">
<label for="password_confirm" class="col-md-2 col-form-label">{{ __('Confirm password') }}</label>
<div class="col-md-6">
<input id="password_confirm" name="password_confirm" type="password" class="form-control" required
autofocus>
</div>
</div>
<div class="form-group login-row row mb-0">
<div class="col-md-8 offset-md-2">
<button type="submit" class="btn btn-primary">
{{ __('Submit') }}
</button>
</div>
</div>
</form>
The result should return 422/error message at least into the console when 'Current password' is wrong, not just redirect back to view and when the password is correct then return 200/success message (not implemented yet.) to console or view.
try this
public function updatePassword(Request $request){
if (!(Hash::check($request->get('old_password'), Auth::user()->password))) {
// The passwords not matches
//return redirect()->back()->with("error","Your current password does not matches with the password you provided. Please try again.");
return response()->json(['errors' => ['current'=> ['Current password does not match']]], 422);
}
//uncomment this if you need to validate that the new password is same as old one
if(strcmp($request->get('old_password'), $request->get('new_password')) == 0){
//Current password and new password are same
//return redirect()->back()->with("error","New Password cannot be same as your current password. Please choose a different password.");
return response()->json(['errors' => ['current'=> ['New Password cannot be same as your current password']]], 422);
}
$validatedData = $request->validate([
'old_password' => 'required',
'new_password' => 'required|string|min:6|confirmed',
]);
//Change Password
$user = Auth::user();
$user->password = Hash::make($request->get('new_password'));
$user->save();
return $user;
}
Laravel 5.8
Include this function in a controller:
public function updatePassword(Request $request)
{
$request->validate([
'password' => 'required',
'new_password' => 'required|string|confirmed|min:6|different:password'
]);
if (Hash::check($request->password, Auth::user()->password) == false)
{
return response(['message' => 'Unauthorized'], 401);
}
$user = Auth::user();
$user->password = Hash::make($request->new_password);
$user->save();
return response([
'message' => 'Your password has been updated successfully.'
]);
}
Don't forget to send new_password_confirmation as a parameter too, because when we use the validation rule confirmed for new_password for example, Laravel automatically looks for a parameter called new_password_confirmation in order to compare both fields.
You are validating request fields old_password, new_password and password_confirm here:
$this->validate($request, [
'old_password' => 'required',
'new_password' => 'required|confirmed',
'password_confirm' => 'required'
]);
however your are using request fields current and password to verify current password and set a new one:
if (!Hash::check($request->current, $user->password)) {
// ...
$user->password = Hash::make($request->password);
Validated fields and used fields should be the same.
I have multiple data base connection when I validate name of product I send message product name is exist before to view and here problem is appeared.
Message appeared in view but all form inputs is cleared.
How I recover this problem taking in consideration if product name not exist. validation executing correctly and if found error in validation it appeared normally and form input not cleared.
this my controller code.
public function add(Request $request)
{
// start add
if($request->isMethod('post'))
{
if(isset($_POST['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
$query = dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name']));
if(!$query) {
$product=new productModel();
// start add
$product->name = $request->input('name');
$product->save();
$add = $product->id;
$poducten = new productEnModel();
$poducten->id_product = $add;
$poducten->name = $request->input('name');
$poducten->price = $request->input('price');
$poducten->save();
$dataview['message'] = 'data addes';
} else {
$dataview['message'] = 'name is exist before';
}
}
}
$dataview['pagetitle']="add product geka";
return view('productss.add',$dataview);
}
this is my view
#extends('layout.header')
#section('content')
#if(isset($message))
{{$message}}
#endif
#if(count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
<form role="form" action="add" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="box-body">
<div class="form-group{{$errors->has('name')?'has-error':''}}">
<label for="exampleInputEmail1">Employee Name</label>
<input type="text" name="name" value="{{Request::old('name')}}" class="form-control" id="" placeholder="Enter Employee Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="text" name="price" value="{{Request::old('price')}}" class="form-control" id="" placeholder="Enter Employee Email Address">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="add" class="btn btn-primary">Add</button>
</div>
</form>
#endsection
this is my route
Route::get('/products/add',"produtController#add");
Route::post('/products/add',"produtController#add");
You can create your own custom validate function like below. I guess this should help you.
Found it from https://laravel.com/docs/5.8/validation#custom-validation-rules -> Using Closures
$validationarray = $this->validate($request,
[
'name' => [
'required',
'alpha',
function ($attribute, $value, $fail) {
//$attribute->input name, $value for that value.
//or your own way to collect data. then check.
//make your own condition.
if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$value))) {
$fail($attribute.' is failed custom rule. There have these named product.');
}
},
],
'price' => [
'required',
'numeric',
]
]);
First way you can throw validation exception manually. Here you can find out how can you figure out.
Second way (I recommend this one) you can generate a custom validation rule. By the way your controller method will be cleaner.
Im making form via LaravelCollective forms in my app.
I have email changing form with fields:
New e-mail
Confirm Email
Password
I need to validate user password on this form with user password in database. Can i do it via Validate?
My form:
{{ Form::model($user, ['route' => ['profile.email.update']]) }}
<div class="form-group row">
<div class="col-md-12">
<h2>Edytuj email</h2>
<div class="form-group">
<label for="edit-page-email">Nowy adres email</label>
{{Form::text('email',null,['class' => 'form-control', 'id'=>'edit-page-email'])}}
</div>
<div class="form-group">
<label for="edit-page-repemail">Nowy adres email (powtórz)</label>
{{Form::text('email_confirmation',null,['class' => 'form-control', 'id'=>'edit-page-email'])}}
</div>
<div class="form-group">
<label for="edit-page-pass">Twoje hasło</label>
{{Form::password('password',['class' => 'form-control', 'id'=>'edit-page-npass'])}}
</div>
<div class="col-md-12 text-center">
{{Form::submit('Zapisz zmiany',['class' => 'btn btn-primary btm-sm']) }}
Anuluj
</div>
</div>
</div>
{{Form::close()}}
And validation is:
$request->validate([
'email' => 'required|confirmed',
'email_confirmation' => 'required',
'password' => 'required|confirmed',
]);
Any ideas how can i do this?
You can compare a string with the user's stored password using this
$pwd = "secret";
$user = User::find(1);
Hash::check($pwd, $user->password); //returns a boolean
Not sure when you say I need to validate user password on this form with user password in database
However the password and password confirm validation should look like the following
{{ Form::password('password',['class'=> 'form-control','placeholder'=>'Enter your Password']) }}
{{ Form::password('password_confirmation', ['class' => 'form-control','placeholder'=>'Re-enter your Password']) }}
Now your validation rules should be
'password' => 'required|confirmed',
No you cannot do this with built in validation rules of Laravel. Beside, you might already know that Laravel store password using bycrypt method. This is not just a plain string comparison operation too.
So, you need to write your own custom validation to check password, or you can just check password and return error if not matched instead of validation.
Note: The confirmed validation rule is to check one password is matched with another password filed or not. This is basically used to match two password form in single form. Not to check associated hashed password with the email in db.
I have 3 user types :
Admin
Distributor
Internal
I have a problem sign in as user type. ( Internal )
I can sign in when my user type is Admin.
I can sign in when my user type is Distributor.
BUT I can’t sign in when my user type is internal. Wired ????
I look through every single line of my code in my sign-in functions in my AccountController.php.
I didn’t notice any bug there. If you guys notice any bugs there -- please kindly let me know.
That will be a huge help for me.
Here is my Sign-In Functions
GET
public function getSignIn(){
return View::make('account.signin');
}
POST
public function postSignIn() {
$validator = Validator::make( Input::only('username','password'),
array(
'username' =>'required',
'password' =>'required'
)
);
if ($validator->fails()) {
return Redirect::route('account-sign-in-post')
->with('error','Username/Password Wrong or account has not been activated !')
->withErrors($validator);
}
// Remember Me
$remember = (Input::has('remember')) ? true : false ;
$auth = Auth::attempt(array(
'username' => strtolower(Input::get('username')),
'password' => Input::get('password'),
'active' => 1),
$remember);
// Keep track on log-in information of the user.
if(Auth::check()){
$user = Auth::user();
$user->last_logged_in = Input::get('created_at');
$user->logged_in_count = $user->logged_in_count + 1 ;
$user->is_online = '1';
$user->save();
}
if($auth) {
return Redirect::to('/')
->with('success','You have been successfully logged in.')
;
}
else {
return Redirect::route('account-sign-in')
->with('error','Username/Password Wrong or account has not been activated !')
->withInput(Input::except('password'))
->withErrors($validator);
}
}
VIEW
#extends ('layouts.form')
#section('content')
<style type="text/css">
.signin{
text-align: center;
}
#forgetpassword{
/*color:#5cb85c;*/
color:silver;
}
</style>
<form class="form-horizontal" role="form" action=" {{ URL::route('account-sign-in-post')}}" method="post" >
#if ($errors->has('username')){{ $errors->first('username')}} #endif
<div class="form-group">
<label for=""> Email </label>
<input placeholder="Email" type="text" class="form-control" required name="username" {{ ( Input::old('username')) ? 'value="'.e(Input::old('username')).'"' : '' }}>
</div><br>
#if ($errors->has('password')){{ $errors->first('password')}} #endif
<div class="form-group">
<label for=""> Password </label>
<input placeholder="Password" type="password" class="form-control" required name="password">
</div><br>
<br>
<button type="submit" class="btn btn-success btn-sm btn-block ">Sign In </button>
{{ Form::token() }}
</form><br>
<div class="col-lg-12 text-center">
<a id="forgetpassword" href="{{ URL::route('account-forgot-password') }}"> Forget Password </a> <br>
</div>
#stop
I am sure that I typed in the right username and password because I double check with my database.
It keep redirecting me back to my sign-in page.
with('error','Username/Password Wrong or account has not been activated !')
Can someone please tell me, if I did anything that I’m not suppose to ?
In your situation, you should check your auth variable in your Sign_In Function.
According to your code,
$auth = Auth::attempt(array(
'username' => strtolower(Input::get('username')),
'password' => Input::get('password'),
'active' => 1),
$remember);
Keep in mind that, these are things need to make sure
username must match the database
password must match the database
user active must be 1
If any of these fail, therefore, it STOP you from signing in.
Since, you're so sure about username and password, what about user active ?
Did you check to if it's 1 ?
If Not
on your set-password function or anywhere, where you normally set your user active.
just do this :
$user->active = '1';
$user->save();
Let me know if this work!!