Laravel mass assignment not saving fields - php

I have 2 tables within one function that I'd like to save data to. One is the Users table, and the second one is a Clinic table.
My user's table is currently working correctly, but I'm unsure if it's 'best practice':
$user = User::create([
'name' => Str::title($request->get('name')),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password'))
])
->clinic()->create($request->only([
'name' => Str::title('clinic_name'),
'telephone',
'address_1',
'address_2',
'city',
'postcode'
]));
My problem occurs at the 'name' column of the Clinic table. It just doesn't save it, even though it's in the $fillable array in my Clinic column:
protected $fillable = ['user_id', 'name', 'telephone'', 'address_1',
'address_2', 'city', 'postcode'];
I have attempted to 'Chain' the methods together, as I want to save the 'user_id' within the Clinic table because they're related.
Many thanks for your help.

You're overriding the name key in your $request->only() call:
$user = User::create([
'name' => Str::title($request->get('name')),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password'))
])->clinic()->create($request->only([
'name' => Str::title('clinic_name'), // This is overriding your 'name' field.
'telephone',
'address_1',
'address_2',
'city',
'postcode'
]));
If you want to run Str::title() over the requests clinic_name, you'll need to assign the attributes manually like so:
$user = User::create([
'name' => Str::title($request->get('name')),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password'))
])->clinic()->create([
'name' => Str::title($request->get('clinic_name')),
'telephone' => $request->get('telephone'),
'address_1' => $request->get('address_1'),
'address_2' => $request->get('address_2'),
'city' => $request->get('city'),
'postcode' => $request->get('postcode'),
]);
Note: Just as a tip, you can also just retrieve request input as a property like so:
->create([
'name' => $request->name // Performs $request->get('name').
])

You can't have 'name' => Str::title('clinic_name') when using create(), it must be a single key as 'name'.
You can use the following before creating the user:
$request->replace('name' => Str::title('clinic_name'));

Related

How to make two columns of a table requiring to be unique at user request

I have tried validating the user request like this:
$data = $request->validate([
'fname' => 'nullable',
'lname' => 'nullable',
'gender' => 'required',
'mobile' => 'required|unique:users,usr_name',
'ncode' => 'nullable',
'password' => 'required',
'password_confirmation' => 'required',
]);
That the mobile filed value must be unique:users,usr_name but I do need to check that it is unique at members table as well (the mbr_mobile column):
unique:members,mbr_mobile
So how to combine these two rules at once?
Just specifying the model name should work.
'mobile' => 'required|unique:User|unique:Members',
But you may specify the column name too.
'mobile' => 'required|unique:User, mobile|unique:Member,mbr_mobile',
You can do it exact,y same way as for users table :
$data = $request->validate([
'fname' => 'nullable',
'lname' => 'nullable',
'gender' => 'required',
'mobile' => 'required|unique:users,usr_name|unique:members,mbr_mobile',
'ncode' => 'nullable',
'password' => 'required',
'password_confirmation' => 'required',
]);

Laravel: Handle unique on Update

I'm using the validation for the employee records during an update. There are some fields which should be unique. But during an update of the employee records, the validation for the unique field is being done. I have researched and tried out the solution as well.
But I'm getting this error:
Error Code : 904 Error Message : ORA-00904: "ID": invalid identifier
Position : 71 Statement : select count() as aggregate from
"EMPLOYEES" where " EMAIL" = :p0 and "ID" <> :p1 Bindings :
[ad#sdfdsf.com,3336] (SQL: select count() as aggregate from
"EMPLOYEES" where " EMAIL" = ad#sdfdsf.com and "ID" <> 3336)
Here is my attempt for the solution:
public function update(Request $request, int $employee_id) {
$this->validate ( $request, [
'first_name' => "required|max:220|regex:/[a-z]/",
'middle_name' => "max:120",
'last_name' => "required|max:220|regex:/[a-z]/",
'email' => "required|unique:employees, email, $employee_id|regex:/[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}/",
'home_phone' => "unique:employees,home_phone, $employee_id|numeric|regex:/^[09][0-9]{8,9}$/",
'mobile' => "unique:employees,mobile, $employee_id|numeric|regex:/(9)[0-9]{9}/",
'job_id' => 'required',
'department_id' => 'required',
'group_id' => 'required',
'node' => 'required',
'branch' => 'required',
'username' => "required|unique:employees,username, $employee_id|regex:/[A-Za-z0-9][.][A-Za-z0-9]/",
'exchange_username' => "required|unique:employees,exchange_username, $employee_id|regex:/[A-Za-z0-9][.][A-Za-z0-9]/",
'extension' => "unique:employees,extension, $employee_id|numeric|regex:/[0-9]{4}/",
] );
Employee::where ('employee_id', $employee_id )->update ( $request->only ( [
'first_name',
'middle_name',
'last_name',
'email',
'address',
'home_phone',
'mobile',
'job_id',
'department_id',
'group_id',
'branch',
'node',
'name',
'username',
'type',
'exchange_username',
'toggle_ivr_access',
'extension',
'attributed_team',
'cable_team_id',
'disable',
] ) );
Session::flash ( 'message', 'The Employee is Successfully Updated.' );
return redirect ()->route ( 'employees.index' );
}
Forcing A Unique Rule To Ignore A Given ID:
Sometimes, you may wish to ignore a given ID during the unique check.
For example, consider an "update profile" screen that includes the
user's name, e-mail address, and location. Of course, you will want to
verify that the e-mail address is unique. However, if the user only
changes the name field and not the e-mail field, you do not want a
validation error to be thrown because the user is already the owner of
the e-mail address.
To instruct the validator to ignore the user's ID, we'll use the Rule
class to fluently define the rule. In this example, we'll also specify
the validation rules as an array instead of using the | character to
delimit the rules:
use Illuminate\Validation\Rule;
Validator::make($data, [
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
]);
I figured out the mistake and successfully find out the solution. Here is the working solution in case anyone is facing the similar problem. I had to pass the employee_id of the single user whereas I was passing the employee_id of the multiple users.
public function update(Request $request, int $employee_id) {
$this->validate ( $request, [
'first_name' => "required|max:220|regex:/[a-z]/",
'middle_name' => "max:120",
'last_name' => "required|max:220|regex:/[a-z]/",
'email' => "required|unique:employees,email,".$employee_id.',employee_id|regex:/[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}/',
'home_phone' => "unique:employees,home_phone,$employee_id,employee_id|numeric",
'mobile' => "required|unique:employees,mobile,$employee_id,employee_id|numeric",
'job_id' => 'required',
'department_id' => 'required',
'group_id' => 'required',
'node' => 'required',
'branch' => 'required',
'username' => "required|unique:employees,username,".$employee_id.',employee_id|regex:/[A-Za-z0-9][.][A-Za-z0-9]/',
'exchange_username' => "required|unique:employees,exchange_username,".$employee_id.',employee_id|regex:/[A-Za-z0-9][.][A-Za-z0-9]/',
'extension' => "required|unique:employees,mobile,$employee_id,employee_id|numeric|regex:/[0-9]{4}/",
] );
Employee::where ('employee_id', $employee_id )->update ( $request->only ( [
'first_name',
'middle_name',
'last_name',
'email',
'address',
'home_phone',
'mobile',
'job_id',
'department_id',
'group_id',
'branch',
'node',
'name',
'username',
'type',
'exchange_username',
'toggle_ivr_access',
'extension',
'attributed_team',
'cable_team_id',
'disable',
] ) );
Session::flash ( 'message', 'The Employee is Successfully Updated.' );
return redirect ()->route ( 'employees.index' );
}

Laravel, blank record using create method

I have a problem with create() method in Laravel.
Every time when I try to create new record in database using this code:
$website = Website::create([
'user_id' => auth()->user()->id,
'name' => $request->name,
'url' => $request->url,
'description' => $request->description,
'subcategory_id' => $request->subcategory_id,
'user_id' => $request->subcategory_extra_id,
]);
the column user_id (in database) equals to 0 whereas my id is 1. Of course I have fillable variable in my model:
protected $fillable = [
'user_id',
'name',
'url',
'description',
'subcategory_id',
];
I tried to use constant value instead of auth()->user()->id but I still have 0 as user_id in database. Using save() method solves this problem but I prefer to use create().
You have listed user_id twice in your keys. The 2nd time, the integer is empty.
'user_id' => $request->subcategory_extra_id,
//observe
Why you used 'user_id two times in your code?
one is
'user_id' => auth()->user()->id,
and another one is
'user_id' => $request->subcategory_extra_id,
Just use one instead of two. And try to use the follwing way:
'user_id' => Auth::user()->id;
Remember: in this case you have to use the namespace of Auth class.
Hope it will work
try to use this
use Auth namespace
and then
$website = Website::create([
'user_id' => Auth::user()->id,
'name' => $request->name,
'url' => $request->url,
'description' => $request->description,
'subcategory_id' => $request->subcategory_id,
]);

Laravel not storing phone number

I am working on a school project, and I have a registration form.
I am working in laravel 5 and am using the auth package of laravel.
I added my extra registration forms like this
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'lastName' => 'required|string|max:55|',
'streetAdress' => 'required|string|max:255|',
'houseNumber' => 'required|integer|min:1|',
'city' => 'required|string|max:255|',
'postal_code' => 'required|string|max:255|',
'user_phone_number' => 'required|numeric|min:10|',
'birth_day' => 'required|date|min:1|',
'user_parent_name' => 'required|string|max:255|',
'user_parent_email' => 'required|email|max:255|',
'user_parent_phone' => 'required|numeric|min:10|',
]);
}
That is my validator here is my create
protected function create(array $data)
{
$birthday = explode('-', $data['birth_day']);
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'lastName' => $data['lastName'],
'streetAdress' => $data['streetAdress'],
'houseNumber' => $data['houseNumber'],
'city' => $data['city'],
'user_phone_number' => $data['user_phone_number'],
'postal_code' => $data['postal_code'],
'birth_day_day' => $birthday[2],
'birth_day_month' => $birthday[1],
'birth_day_year' => $birthday[0],
'user_parent_name' => $data['user_parent_name'],
'user_parent_email' => $data['user_parent_email'],
'user_parent_phone' => $data['user_parent_phone'],
]);
}
Here is my html
<input id="user_phone_number" type="number" class="form-control" name="user_phone_number" value="{{ old('user_phone_number') }}" required>
In my database I have a column called user_phone_number. Everything else does store but the user_phone_number is still NULL
Thanks in advance
I was looking through my model and i found the problem. i didnt had the fillable option for user_phone_number,
protected $fillable = [
'name', 'email', 'password', 'lastName', 'streetAdress', 'houseNumber', 'city',
'postal_code', 'birth_day_year', 'user_phone_number', 'birth_day_month', 'birth_day_day', 'user_parent_name',
'user_parent_email', 'user_parent_phone',
];
Was missing user_phone_number
**if you are store phone no in database use this migration work for me
$table->bigInteger('phone');

Create record with Relation Laravel 5.1

Hi i have the next code for create my records
Institution::create($request->all());
User::create([
'name' => $request['name'],
'lastname' => $request['lastname'],
'phone' => $request['phone'],
'email' => $request['email'],
'password' => $request['password'],
'state' => 1,
'profile_id' => 1,
'institution_id' => Institution::max('id'),
]);
The last attributes for the User thats correct implement so?
The last 3 user attributes , it is correct to do it that way? or is there a better
Using Institution::max('id') creates a race condition. Since the create() static method of Eloquent::Model returns the newly-created model, you can just do:
$institution = Institution::create($request->all());
User::create([
'name' => $request['name'],
'lastname' => $request['lastname'],
'phone' => $request['phone'],
'email' => $request['email'],
'password' => $request['password'],
'state_id' => 1,
'profile_id' => 1,
'institution_id' => $institution->id,
]);
Creating a record with known parent ids is generally fine if your goal is to minimize the number of database queries and you have the ids of the related models.
Another way to do it, though it triggers more update queries, is to use Eloquent's built-in methods for adding related models. For example:
$institution = Institution::create($request->all());
$state = State::find(1);
$profile = Profile::find(1);
$user = new User([
'name' => $request['name'],
'lastname' => $request['lastname'],
'phone' => $request['phone'],
'email' => $request['email'],
'password' => $request['password']
]);
$user->state()->associate($state);
$user->profile()->associate($profile);
$user->profile()->associate($institution);
$user->save();
However, in this situation, since the related models are not already loaded, and you know their ids, there is no need to fetch them only to associate them with the User.

Categories