I'm trying to submit form with two input. One input name is 'name' and second name is 'username' and username is unique. Form not saving when I'm trying to submit. How can I solve this problem?
My controller is:
public function profileSettingsPost(request $request){
$request->validate([
'name' => ['nullable','string', 'max:64'],
'username' => ['nullable','string','max:16','unique:users'],
]);
$user = Auth::user();
$user->name = $request->name;
$user->username = $request->username;
if($user->save()){
return redirect()->route('getProfile',['username'=>$user->username]);
}else{
return back();
}
try this:
$input = $request->all();
$rules = [
name' => ['nullable', 'string', 'max:64'],
username' => ['nullable','string','max:16','unique:users,username_column']
];
$massages = [] ;
$fieldNames = [];
$validation = Validator::make($input, $rules, $massages, $fieldNames);
if($validation->fails()){
return redirect()->route('getProfile',['username'=>$user->username]);
}else {
return back();
}
and don't forget to type hint user Model and validation Facade
use App\Models\User;
use Illuminate\Support\Facades\Validator;
Related
I am trying to perform validation without passing the $request variable, would someone be able to provide what I pass through the validator function? My code is below
public function change($id)
{
$user = User::find($id);
$user->name = request("name");
$user->date_of_birth = request("date");
$user->email = request("email");
$user->phone = request("phone");
$user->address = request("address");
$user->city = request("city");
$user->postcode = request("postcode");
$validator = Validator::make(request(), [
'name' => 'required',
'email' => 'email|string|max:255|unique:users',
'phone' => 'required|numeric',
'address' => 'required|numeric',
'postcode' => 'required|numeric',
'city' => 'required'
]);
if ($validator->fails()) {
return redirect("/user/edit")
->withErrors($validator)
->withInput();
}
$user->save();
return redirect('/user');
}
Again, i am trying this without $request
Any help would be appreciated!
You can do by passing an array, so all() returns all the fields passed, try using it like this:
$validator = Validator::make(request()->all(), ...
Another tip is to first make the validation then find the user and set its fields. The validation can be a guard in this case. You can also create a custom Form request and set the validation rules there.
You can use facade to fetch that data and pass it to validator,
$input = Request::all();
Here is the documentation.
If you don't want to use the $request you can just use the request() helper instead. For example:
$user = User::find($id);
$user->name = request("name");
$user->date_of_birth = request("date");
$user->email = request("email");
$user->phone = request("phone");
$user->address = request("address");
$user->city = request("city");
$user->postcode = request("postcode");
request()->validate([
'name' => 'required',
'email' => 'email|string|max:255|unique:users',
'phone' => 'required|numeric',
'address' => 'required|numeric',
'postcode' => 'required|numeric',
'city' => 'required'
])
$user->save();
return redirect('/user');
That works fine unless you want to specifically handle failed validation in a different way.
If you can't use $request, please use request helper which can be used as Request::all(); or request->all();
I'm using Laravel 5.3's validation as follows:
In my model:
public static $validation = [
'name' => 'required',
'username' => 'required|alpha|unique:companies',
'email' => 'required|email|unique:companies',
];
In my controller, I post to the same CompanyController#dataPost method when creating a new item or when editing one:
public function dataPost(Request $request) {
// First validation
$this->validate($request, Company::$validation);
$id = $request->id;
if ($id > 0) {
// Is an edit!
$company = Company::find($id);
$company->update($request->all());
$company->save();
Session::flash('messageclass', 'success');
Session::flash('message', trans('companies.editedsuccessfully'));
} else {
// Is a create
$company = new Company($request->all());
$company->save();
Session::flash('messageclass', 'success');
Session::flash('message', trans('companies.createdsuccessfully'));
}
return redirect()->route('companyindex');
}
The unique validation works ok when I create a new item, but causes an error (as in it flags the username as already existing) when editing an item.
Any idea how to avoid this? Even in an edit I'd still want to ensure the data is unique if it's changed, but if the value is the same as before then ignore the validation.
I know I could do this manually, but I wonder if there is a built-in way to avoid this.
Thanks!
I think you can try this:
public static $validation = [
'name' => 'required',
'email' => Auth::check()
? 'required|email|unique:companies,email,'.Auth::id()
: 'required|email|unique:companies,email',
'username' => Auth::check()
? 'required|alpha|unique:companies,username,'.Auth::id()
: 'required|alpha|unique:companies,username',
];
Hope this work for you !!!
You can update email field with unique property as well.
Following rule will check uniqueness among all emails in other column except current one.
Try this one,
'email' => 'required|unique:users,email,' . $userId
here $userId refers to id of user currently updated.
You can see official docs here
You can create different validation methods for insert or update
public static $validation_update = [
'name' => 'required',
'username' => 'required|alpha',
'email' => 'required|email',
];
public static $validation_add = [
'name' => 'required',
'username' => 'required|alpha|unique:companies',
'email' => 'required|email|unique:companies',
];
Then apply validation in condition
public function dataPost(Request $request) {
// First validation
$id = $request->id;
if ($id > 0) {
// Is an edit!
$this->validate($request, Company::$validation_update);
$company = Company::find($id);
$company->update($request->all());
$company->save();
Session::flash('messageclass', 'success');
Session::flash('message', trans('companies.editedsuccessfully'));
} else {
// Is a create
$this->validate($request, Company::$validation_add);
$company = new Company($request->all());
$company->save();
Session::flash('messageclass', 'success');
Session::flash('message', trans('companies.createdsuccessfully'));
}
return redirect()->route('companyindex');
}
$id = $request->id;
if ($id > 0) {
// Is an edit!
$this->validate($request, Company::$validation_update);
$company = Company::find($id);
$company->update($request->all());
$company->save();
I am using use Illuminate\Http\Request to access form request. For example if my form request is coming from http://localhost:8012/test_project/public after validating it is automatically redirecting to http://localhost:8012/test_project/public with error messages but i want it to redirect to http://localhost:8012/test_project/public#myform because my form is visible in #myform section. So how can we do it. I am using Laravel 5.0
Following is my method code in controller that handles my request
public function add_user(Request $request){
$this->validate($request, [
'name' => 'required|min:3',
'email' => 'required|email|unique:users,email',
'mobile' => 'required|regex:/^[789]\d{9}+$/|unique:users,mobile',
'pass' => 'required|min:6',
'cpass' => 'required|same:pass'
]);
$user = new Myuser;
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->mobile = $request->input('mobile');
$user->pass = md5("EEE".$request->input('pass'));
$user->register_on = date('Y-m-d');
$user->user_type = 'Free';
$user->last_login = date('Y-m-d H:i:s');
$user->status = 'Active';
$user->save();
$insertedId = $user->sno;
$uid = "UID".$insertedId;
Myuser::where('sno', $insertedId)
->update(['uid' => $uid]);
//echo $insertedId;
return redirect('')->with('message', 'Registered Successfully');
}
If you make your own Validator instead of using $this->validate(), you can have more control over what happens on a failed validation. Here is an example from the laravel documentation. Make sure you add use Validator; to the top of your php file. https://laravel.com/docs/5.3/validation
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
User_code is generated and must be unique. What would be the easiest/cleanest way to do retry logic on this model save? I would like to verify the generated code first, and then if it's not found on the users table, create the user, if found, loop to retry. What would be the syntax for that? Thanks
public function create(array $data)
{
$user = User::create([
'user_name' => 'My user name',
'user_code' => bin2hex(openssl_random_pseudo_bytes(16))
]);
$user->save();
return $user;
}
Why don't you check the database when generating the code? That way, you only try to create once you got it right and the end user doesn't have to face an error that is not up to him/her.
do {
$code = bin2hex(openssl_random_pseudo_bytes(16));
$record = User::where('user_code', $code)->get();
} while(!empty($record));
$user = User::create([
'user_name' => 'My user name',
'user_code' => $code
]);
return $user;
You could avoid the retry:
public function create(Request $request)
{
$request->merge(['user_code' => bin2hex(openssl_random_pseudo_bytes(16))]);
$this->validate($request, [
'user_name' => 'required|unique:users',
'user_code' => 'required|unique:users',
]);
$user = new User;
$user->user_name = $request->user_name;
$user->user_code = $request->user_code;
$user->save();
return $user;
}
You should create a unique string from the beginning. Still go for validation, of course.
public function create(Request $request)
{
$user_code = bcrypt($request->user_name . openssl_random_pseudo_bytes(16));
$request->merge(['user_code' => $user_code]);
$this->validate($request, [
'user_name' => 'required|unique:users',
'user_code' => 'required|unique:users',
]);
$user = User::create($request);
return $user;
}
A save() is implied by create().
Hi I am using Laravel and I am using a couple of packages for user auth and roles which are Zizaco Confide and I want to update the users password firstly they should input there current password a new password and confirm the password and they should match. Now the validation works but the users password isn't updated in the database. My code is below:
public function updatePassword($id) {
$rules = array(
'now_password' => 'required',
'password' => 'min:5|confirmed|different:now_password',
'password_confirmation' => 'required_with:password|min:5'
);
//password update.
$now_password = Input::get('now_password');
$password = Input::get('password');
$passwordconf = Input::get('password_confirmation');
$validator = Validator::make(Input::only('now_password', 'password', 'password_confirmation'), $rules);
if ($validator->fails()) {
return Redirect::back()->withErrors($validator);
}
elseif (Hash::check($now_password, Auth::user()->password)) {
$user = User::find($id);
$user->password = Hash::make($password);
$user->save();
return Redirect::back()->with('success', true)->with('message','User updated.');
} else {
return Redirect::back()->withErrors('Password incorrect');
}
}
Any ideas why the users password is not isn't updated using this block of code
$user = User::find($id);
$user->password = Hash::make($password);
$user->save();
User Model
<?php
use Zizaco\Confide\ConfideUser;
use Zizaco\Confide\ConfideUserInterface;
use Zizaco\Entrust\HasRole;
class User extends Eloquent implements ConfideUserInterface
{
use SoftDeletingTrait;
use ConfideUser;
use HasRole;
protected $softDelete = true;
public function favourites()
{
return $this->hasMany('Favourite');
}
}
To check inputted password:
1.
$now_password = Input::get('now_password');
$user = DB::table('users')->where('name', Auth::user()->name)->first();
if(Hash::check($now_password, $user->password)){
//Your update here
}
2.
$now_password = Input::get('now_password');
if(Hash::check($now_password, Auth::user()->password)){
//Your update here
}
To check if they match and if the new password is different than old.
$rules = array(
'now_password' => 'required|min:8',
'password' => 'required|min:8|confirmed|different:now_password',
'password_confirmation' => 'required|min:8',
);
And edit your form to (or enter your names):
{{ Form::label('now_password', 'Old Password') }}
{{ Form::password('now_password')}}
{{ Form::label('password', 'New Password') }}
{{ Form::password('password')}}
{{ Form::label('password_confirmation', 'Confrim New Password') }}
{{ Form::password('password_confirmation')}}
Update
Ok, so you don't want to edit only passwords.
Edit your rules:
$rules = array(
'now_password' => 'required|min:5',
'password' => 'min:5|confirmed|different:now_password',
'password_confirmation' => 'required_with:password|min:5'
);
I think that current password should be required in every type of change. Other inputs imo shouldn't be required, because you don't know which data user want to edit.
You should also add to your rules something like:
'username' => alpha_num|unique:users,username
etc.. (for more see http://laravel.com/docs/4.2/validation#available-validation-rules)
If Validator pass, you should check which data user want to change (which inputs are not empty).
Something like:
if(!empty(Input::get('firstname'))){
$user->firstname = Input::get('firstname');
}
etc...with every input.
Try it like this:
public function updatePassword($id)
{
$user = User::findOrFail($id);
User::$rules['now_password'] = 'required';
// other rules here
$validator = Validator::make($data = Input::all(), User::rules('update', $id));
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
array_forget($data, 'password_confirmation');
array_forget($data, 'now_password');
$data['password'] = Hash::make($data['password']);
$user->update($data);
return Redirect::back()->with('success', true)->with('message','User updated.');
}
remember your password confirmation field name must be "password_confirmation" if you used first way...
if you used another name for password confirm field you can use second way.
$this->validate($request, [
'email' => 'required|unique:user|email|max:255',
'username' => 'required|max:20',
'password' => 'required|min:3|confirmed',
'password_confirmation' => 'required',
'gender' => 'required|in:m,f',
]);
$this->validate($request, [
'email' => 'required|unique:user|email|max:255',
'username' => 'required|max:20',
'password' => 'required|min:3',
'confirm_password' => 'same:password',
'gender' => 'required|in:m,f',
]);
public function change_password_post($id)
{
$rules = array(
'current' => 'required|string|min:8',
'new' => 'required|string|min:8',
'confirm' => 'required|same:new'
);
$validator = Validator::make(Input::only('current', 'new', 'confirm'), $rules);
if($validator->fails())
{
return Redirect::back()
->withErrors($validator);
}
else
{
$users = User::where('id', '=', $id)->first();
if (Hash::check(Input::get('current'), $users->password))
{
if(Input::get('new') == Input::get('confirm'))
{
$users->password =Hash::make(Input::get('new'));
$users->save();
$msg = array('msg' => 'Password changed Successfully');
return Redirect::back()
->withErrors($msg);
}
else
{
$msg = array('msg' => 'New password and Confirm password did not match');
return Redirect::back()
->withErrors($msg);
}
}
else
{
$msg = array('msg' => 'Current password is incorrect');
return Redirect::back()
->withErrors($msg);
}
}
}