I have this following problem while trying to Edit data already existing in my database.
my controller name is UserController.php
Error: Creating default object from empty value.
I can Pull data from my database and post it in my form. when trying editing that error occurs.
Here is the block of code that causes the error.
public function update(Request $request, $id)
{
$this->validate($request, [
'fname' => 'required',
'lname' => 'required',
'email' => 'required',
'phone' => 'required',
'address' => 'required',
'country' => 'required',
'city' => 'required',
'bday' => 'required',
'username' => 'required',
'password' => 'required',
'access' => 'required'
]);
$userList = users::find($id);
$userList->fname = $request->get('fname');
$userList->lname = $request->get('lname');
$userList->email = $request->get('email');
$userList->phone = $request->get('phone');
$userList->address = $request->get('address');
$userList->country = $request->get('country');
$userList->city = $request->get('city');
$userList->bday = $request->get('bday');
$userList->username = $request->get('username');
$userList->password = $request->get('password');
$userList->access = $request->get('access');
$userList->save();
return redirect()->route('users.index')->with('success', 'Data Updated');
}
I can see from the debugger that I send the new data
GET Data empty
POST Data
_token "mnC6GliLHdSazZkEpaxZQ97aAChr2LObcc9clMlk"
_method "PATCH"
fname "test"
lname "user"
email "test#user.lara"
phone "12345678990"
address "Streat"
country "countryplace"
city "somecity"
bday "2018-01-01"
username "tester"
password "test"
access "Client"
But It highlights $userList->fname = $request->get('fname');
and says : "Creating default object from empty value"
I am new to laravel and cant understand why this is happening.
is it because of my form?
<form method="post" action="{{action('UserController#update','$id')}}">
{{csrf_field()}}
<input type="hidden" name="_method" value="PATCH" />
I think the problem is here:
<form method="post" action="{{action('UserController#update','$id')}}">
You should not use quotes for $id, it should be:
<form method="post" action="{{action('UserController#update',$id)}}">
Now because you have quotes, in line:
$userList = users::find($id);
no user is found, because in fact it's doing:
$userList = users::find('$id');
Related
How to add id in stud_num just like in email and username? the codes found in User Controller.
public function update(Request $request, $id)
{
$this->validate($request, [
'first_name' => 'required|max:255|regex:/^([^0-9]*)$/',
'middle_name' => 'nullable|max:255|regex:/^([^0-9]*)$/',
'last_name' => 'required|max:255|regex:/^([^0-9]*)$/',
'contact' => ['required', 'regex:/^(09|\+639)\d{9}$/'],
'course' => 'required',
'role_as' => 'required',
'stud_num' => ['required', 'unique:users,stud_num', 'max:15', new StrMustContain('TG')],
'username' => 'required|alpha_dash|unique:users,username,' . $id,
'email' => 'required|email:rfc,dns|unique:users,email,' . $id
]);
// codes for update
}
Just add id like email and username.
'stud_num' => ['required', 'unique:users,stud_num,'.$id, 'max:15', new StrMustContain('TG')]
you can write it like this:
'stud_num'=>['required',Rule::unique('users','stud_num')->ignore($id),'max:15',new StrMustContain('TG')]
I have create a validation request file on request folder. It working fine in new insert. But when i update, it's not working also i pass the unique $id but not working.
a. Resource controller update method
public function update(KlassNameRequest $request, $id)
{
$validated = $request->validated();
KlassName::where('id', $id)->update($validated);
}
b. Validation code
public function rules()
{
return [
'name' => 'required|unique:klass_names|max:128,' . $this->id,
'ref' => 'required|unique:klass_names|numeric|between:1,999,' . $this->id,
'seat_quota' => 'required|numeric|between:1,9999',
'division' => 'required',
'semester' => 'required',
];
}
This message shows me when i update
return [
'name' => 'required|unique:klass_names,' . $this->id.'|max:128',
'ref' => 'required|unique:klass_names,' . $this->id.'|numeric|between:1,999',
'seat_quota' => 'required|numeric|between:1,9999',
'division' => 'required',
'semester' => 'required',
];
Just try this one
'name' => ['required','max:128',Rule::unique('klass_names')->where(function ($query) {
return $query->where('name', $this->name);
})],
'ref' => ['required','max:128',Rule::unique('klass_names')->where(function ($query) {
return $query->where('ref', $this-> ref);
})],
Hope it will solve the problem 😊
I have solve my problem in this way -
a. Add extra input hidden field passing id for $request method. Because my route is resource group route -
<form action="{{ route('adm.kls.update', $kls->id) }}" method="post">
#csrf
#method('PUT')
<input type="hidden" name="id" value="{{ $kls->id }}">
</form>
b. Some editing in validation code.
public function rules() {
return [
'name' => 'required|max:128|unique:klass_names,name,' . $this->id,
'ref' => 'required|numeric|between:1,999|unique:klass_names,ref,' . $this->id,
'seat_quota' => 'required|numeric|between:1,9999',
];
}
done.
I have a method that stores employee data on create however I have defined a default password to be randomly created and hashed. The password isn't stored for some reason.
Any ideas?
public function store(Request $request)
{
// get company
$company = Auth::user()->companies()->first();
// get and validate data
$storeData = $request->validate([
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required|email',
'phone' => 'required|numeric|digits:11'
]);
// create employee with validated data
$employee = $company->employees()->create(array_merge($storeData), [
'password' => Hash::make(Str::random(40)),
]);
return redirect('/employees/' . $employee->id )
->with('success', 'Employee successfully created');
}
There's an typo in your code, try
$employee = $company->employees()->create(array_merge($storeData, [
'password' => Hash::make(Str::random(40)),
]));
The array_merge is closed too early and only contains what you have in the $storeData array.
I have a login page http://localhost/register the register method displays the register page. I am posting the data and validating it in this way
$rules = array(
'telephone' => 'required',
'theemail' => 'required',
'fullnames' => 'required',
'profilepicture' => 'required',
'password' => 'required',
'confirm-password' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
$messages = $validator->messages();
return Redirect::back()->withErrors($validator);
}
I used the method above to validate a form but when i try the above code, it seems not to validate. My last app was simplistic and the form names were also the column names in the database.
In my case, the array
$rules = array(
'telephone' => 'required',
'theemail' => 'required',
'fullnames' => 'required',
'profilepicture' => 'required',
'password' => 'required',
'confirm-password' => 'required'
);
does not contain names of columns. Must the rules contain the column names of the table i am writing to?.
Try something like this:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'telephone' => 'required',
'theemail' => 'required',
'fullnames' => 'required',
'profilepicture' => 'required',
'password' => 'required',
'confirm-password' => 'required'
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
}
Be sure to match the column name in the $rule array with the other in the DB table, and if you mean the validation error doesn't appear, then you have to put this in the blade file which you want to show in.
#if(!empty($errors))
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
of course you have to add the needed classes
I have 1 form, with multiple inputs. each section can have multiple inputs, I want to create a Form Validator inside Requests for they, but don't know how to do it... This is currently how I am doing it:
public function postCreateResume(Request $request, Resume $resume, Education $education)
{
/*
* begin a transaction, because we
* are doing multiple queries
*/
DB::beginTransaction();
/*
* first we must create the resume, then we
* can use the id for the following rows
*/
$this->validate($education, [
'resume_title' => 'required',
'expected_level' => 'required',
'salary' => 'required',
'work_location' => 'required',
'year_experience' => 'required',
'about' => 'required',
]);
$resume->name = $request['resume_title'];
$resume->work_level = $request['expected_level'];
$resume->salary = $request['expected_salary'];
$resume->country = $request['work_location'];
$resume->total_experience = $request['year_experience'];
$resume->about = $request['about'];
$resume->save();
// a user can have multiple educations on their cv
foreach($request->input('education') as $education){
$this->validate($education, [
'institution' => 'required',
'degree' => 'required',
'year_begin' => 'required',
'year_finish' => 'required',
'about' => 'required',
]);
// passed our checks, insert
$education->resume_id = $resume->id;
$education->user_id = Auth::user()->id;
$education->institute = $education['institution'];
$education->degree = $education['degree'];
$education->summary = $education['about'];
$education->started = $education['year_begin'];
$education->ended = $education['year_finish'];
if(!$education->save()){
DB::rollback();
return redirect()->back()->withErrors("There was an error creating this resume")->withInput();
}
}
// a user can have multiple employment on their cv
foreach($request->input('experience') as $employment){
$this->validate($employment, [
'company' => 'required',
'title' => 'required',
'country' => 'required',
'year_begin' => 'required',
'year_finish' => 'required',
'notes' => 'required',
]);
// passed our checks, insert
$employment->resume_id = $resume->id;
$employment->user_id = Auth::user()->id;
$employment->name = $employment['title'];
$employment->company = $employment['company'];
$employment->country = $employment['country'];
$employment->started = $employment['year_begin'];
$employment->ended = $employment['year_finish'];
$employment->summary = $employment['notes'];
if(!$employment->save()){
DB::rollback();
return redirect()->back()->withErrors("There was an error creating this resume")->withInput();
}
}
return redirect()->back()->withSuccess("You have created a resume")->withInput();
}
Notice I have the validate inside each of the foreach in case the user has chosen more than 1 (in this example) work experience, or education, what I am trying to do is move the $this->validate inside the Requests folder, how can I achieve this?
I am using a foreach because I can have unlimited sections, see the image as to why;
Since laravel 5.4 you can pass arrays to the validator itself, for exaple
<input name="myarray[0]['test'] type="text">
Can now be validated like so
$this->validate($request, [
'myarray.*.test' => 'required'
]);
https://laravel.com/docs/5.4/validation#validating-arrays
Validating array based form input fields doesn't have to be a pain. For example, to validate that each e-mail in a given array input field is unique, you may do the following:
$validator = Validator::make($request->all(), [
'person.*.email' => 'email|unique:users',
'person.*.first_name' => 'required_with:person.*.last_name',
]);
Likewise, you may use the * character when specifying your validation messages in your language files, making it a breeze to use a single validation message for array based fields:
'custom' => [
'person.*.email' => [
'unique' => 'Each person must have a unique e-mail address',
]
],