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();
Related
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;
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();
My application gives employees of a company the ability to edit their data(example: address). Once they change any of it, a manager gets an e-mail with their new information. The problem is that an email is sent every time a employee clicks update. I need the application to compare the info in the database and only send an email if there's new information. What is good way to achieve this? I am sorry I forgot to mention, the email needs to contain only the new iformation. So isDirty() would not work for me.
public function editcredentials_action(Request $request)
{
$user = Auth::user();
$address = $user->address;
$this->validate($request, [
'password' => 'max:255',
'language' => 'integer',
'facebook_profile' => 'max:255',
'twitter_profile' => 'max:255',
'street' => 'max:255',
'house_number' => 'max:255',
'city' => 'max:255',
'zip_code' => 'max:255',
'country' => 'max:255',
]);
if (!empty($request->get('password')) && $request->get('password')) {
$user->password = bcrypt($request->get('password'));
}
$user->facebook_profile = $request->get('facebook_profile');
$user->twitter_profile = $request->get('twitter_profile');
$user->language_id = $request->get('language');
$user->save();
if (!$address) {
$address = new UserAddress();
$address->user_id = $user->id;
}
$address->street = $request->street;
$address->house_number = $request->house_number;
$address->city = $request->city;
$address->zip_code = $request->zip_code;
$address->country = $request->country;
$address->save();
$data = [
'email' => $user->email,
'facebook' => $user->facebook_profile,
'twitter' => $user->twitter_profile,
'name' => $user->name . ' ' . $user->lastname,
'address' => $address,
];
Mail::send('emails.user-update', $data, function ($message) use ($data) {
$message->from('no-reply#example.com', 'Profile change');
$message->to('profilechange#example.com');
$message->subject('Profile change: ' . $data['name']);
});
Session::flash('message', trans('app.global.saved'));
return back();
//return redirect()->route('profile.edit-credentials');
}
I don't think isDirty() will work here, but you can save user data in the beginning:
$params = ['language', 'facebook_profile', 'twitter_profile', 'name'];
$oldUserData = auth()->user()->only($paramsToCOmpare);
Then compare the data after using save() method:
if (count(array_diff($oldUserData, $user->only($paramsToCompare))) > 0) {
// Data was changed.
}
You can do the same for UserAddress model. For password just check if it was filled in the form (since you're not displaying it anyway):
if (!empty($request->password))
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...
}
So I'm trying to insert values into two tables from a single form using Laravel4.
this is my Store() function.Am i doing it right..?
I know i should be using two controllers AddressController.php and PeopleController.php.., but can i use a single controller to insert into two tables using a single form.?
public function store()
{
$rules = array(
'address_id' => 'required',
'contact_id' => 'required',
'prefix' => 'required',
'firstname' => 'required',
'middlename' => 'required',
'lastname' => 'required',
'suffix' => 'required',
'occupation' => 'required',
'gender' => 'required',
'comment' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
$user= Auth::user();
if (!empty($user->id))
$user_id=$user->id;
// process the login
/*if ($validator->fails()) {
return Redirect::to('people/create')
->withErrors($validator);
} else {*/
// store
$person = new Person;
$person->user_id=$user_id;
$person->address_id =Input::get('address_id');
//$person->contact_id = Input::get('contact_id');
$person->prefix = Input::get('prefix');
$person->firstname =Input::get('firstname');
$person->middlename =Input::get('middlename');
$person->lastname =Input::get('lastname');
$person->suffix =Input::get('suffix');
$person->occupation =Input::get('occupation');
$person->gender =Input::get('gender');
$person->comment =Input::get('comment');
//$person->user_id =Input::get('user_id');
$person->save();
$validator = Validator::make($data = Input::all(), Address::$rules);
$address->address1 = Input::get('address1');
$address->address2 = Input::get('address2');
$address->apt = Input::get('apt');
$address->city = Input::get('city');
$address->state = Input::get('state');
$address->zip = Input::get('zip');
$address->country = Input::get('country');
$address->save();
// redirect
Session::flash('message', 'Successfully created new Employee!');
//return Redirect::to('addresses/create');
return Response::json($person);
}
As long as you've defined a relationship between the person and address models, then you can use the person model's push() method which is designed to save multiple related models in a single step
Note that if you had fillable defined for your models, you could also eliminate a lot of those boilerplate $person->prefix = Input::get('prefix'); statements from your code as well