How do save all request data to database - php

how can save all to Database?
$request->validate([
'name' => 'required',
'email' => 'required',
'street' => 'required',
'street_addition' => 'nullable',
'postal_code' => 'required',
'city' => 'required',
'country' => 'required',
'vat_id' => 'nullable'
]);
$user = Auth::user();
$billingDetail = $user->billingDetails()->save(new UserBillingDetail([
$request->all()
]));
the $request->all() dont work. idk why. it comes
SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a
default value" and email and and and...

The SQL error you are experiencing is because your columns doesn't allow NULL values and it produces this error, when you try and put in a row with empty values.
The reason why your values are empty, is because you're wrapping your UserBillingDetail construct parameter with an []:
$billingDetail = $user->billingDetails()->save(new UserBillingDetail([
$request->all()
]));
This will effectively send an array with a single key (0) containing the value of your request->all(). Hence, the name, email, etc., fields doesn't exist in the top level array (which is what you want).
You should remove the extra brackets, making your code look like this:
$billingDetail = $user->billingDetails()->save(new UserBillingDetail(
$request->all()
));

The error message already give you the answear. you pass data and some fields are empty.
first of all: make sure that this fields not empty. After then check if the fields are declare as fillable in your model. protected $fillable = [...]

Try using $request->except('_token') in place of $request->all() as the request also have _token key in it.

error message already give you the answer. you pass data and some fields are empty. or make the field nullable.

Related

Laravel validate array and exclude on specific array value

I have an array of values that I send together with other fields in a form to laravel.
The array contains a role_id field and a status field, the status can be I (Insert) U (update) D (Delete). When I validate the values in the array I want it to skip the ones where the status equals D. Otherwise I want it to validate.
private function checkValuesUpdate($userid = null)
{
return Request::validate(
[
'displayname' => 'required',
'username' => 'required',
'email' => ['nullable', 'unique:contacts,email' . (is_null($userid ) ? '' : (',' . $userid ))],
'roles.*.role_id' => ['exclude_if:roles.*.status,D', 'required']
]
);
}
I can't seem to get it to work. I've been searching all over the place for functional code as well as the Laravel documentation. But no luck so far. Has anybody ever done this?
Your problem comes from a misunderstanding of the exclude_if rule. It doesn't exclude the value from validation, it only excludes the value from the returned data. So it would not be included if you ran request()->validated() to get the validated input values.
According to the documentation, you can use validation rules with array/star notation so using the required_unless rule might be a better approach. (Note there's also more concise code to replace the old unique rule, and I've added a rule to check contents of the role status.)
$rules = [
'displayname' => 'required',
'username' => 'required',
'email' => [
'nullable',
Rule::unique("contacts")->ignore($userid ?? 0)
],
'roles' => 'array',
'roles.*.status' => 'in:I,U,D',
'roles.*.role_id' => ['required_unless:roles.*.status,D']
];

Laravel Validation rules: required_without

I have two fields: Email and Telephone
i want to create a validation where one of two fields are required and if one or both fields are set, it should be the correct Format.
I tried this, but it doesnt work, i need both though
public static array $createValidationRules = [
'email' => 'required_without:telephone|email:rfc',
'telephone' => 'required_without:email|numeric|regex:/^\d{5,15}$/',
];
It is correct that both fields produce the required_without error message if both are empty. This error message clearly says that the field must be filled if the other is not. You may change the message if needed:
$messages = [
'email.required_without' => 'foo',
'telephone.required_without' => 'bar',
];
However, you must add the nullable rule, so the format rules don't apply when the field is empty:
$rules = [
'email' => ['required_without:telephone', 'nullable', 'email:rfc'],
'telephone' => ['required_without:email', 'nullable', 'numeric', 'regex:/^\d{5,15}$/'],
];
Furthermore: It is recommended writing the rules as array, especially when using regex.

Laravel different validation doesn't work with strings containing numbers

I want to validate a value that I got from a certain form. The value type is text. I want it to match a specific username from the database from the users table, but also to not match the current user's username.
To achieve that, I used the following validation rules:
'username' => [
'required',
'string',
'exists:App\User,username',
'different:' . auth()->user()->username
]
What I've discovered is that whenever the auth()->user()->username value includes a digit, it passes the validation even if request()->username = auth()->user()->username. Is there anything I can do to prevent this from happening?
Thanks in advance.
Use unique like -
Considering id is your user's id.
'username' => 'required|string|unique:username,id,'.auth()->user()->username,
This will check if username is unique or not except this userId.
The answer to this issue was creating own Rule::exists validation, which is shown below:
'username' => [
'required',
'string',
Rule::exists('users')->where(function ($query) {
$query->where('username', '<>', auth()->user()->username);
})
],
I solved a similar problem as follows.
$request->validate([
'email' => ['required', 'email','unique:users,email,'.Auth::id()],
'phone' => ['required', 'unique:users,phone,'.Auth::id()],
]);

General error: 1364 Field 'department_id' doesn't have a default value

here's the error
SQLSTATE[HY000]: General error: 1364 Field 'department_id' doesn't
have a default value (SQL: insert into ms_user (name, username,
role, email, password, updated_at, created_at)
ms_user model
protected $fillable = [
'department_id','name', 'email', 'password','username','role',
];
create function :
{
return ms_user::create([
'name' => $data['name'],
'username' => $data['username'],
'role' => $data['role'],
'email' => $data['email'],
'department_id' => $data['department_id'],
'password' => bcrypt($data['password'])
]);
}
validator function :
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'username' => 'required|string|max:255',
'role' => 'required|in:user,admin',
'department_id' => 'required|string',
'email' => 'required|string|email|max:255|unique:ms_user',
'password' => 'required|string|min:6|confirmed',
]);
}
department_id is a dropdown menu that contains data from the ms_department table,
department_id becomes the foreign key in the ms_user table and as the primary key in the ms_department
It seam that your are trying to create a user with the filed department_id set to null. In your controller it seams your are passing $data['department_id'] I presume that value comme from the Request Object. But as that field doesn't have any value, when you the code to create user is execute, It send and empty value to that database. The table which contain users data doesn't allow that field to be empty.
You solve that by updating you migration to allow null on the departement_field like this
$table->integer('department_id')->nullable();
Or you can check if $data['department_id'] isn't null but using debug($data) in your controller.
it seems you are trying to make a bulk upload if not the name attribute of the input referring to department_id is empty or not correctly spelled
I had the same issue but the error in my case originated from my controller where I interchanged the names of my field living out exp_date
I had the same problem. I checked the stream on which data is passed in.
Check if everything on view is ok.
Check if everything on controller is fine.
Check if field exists in model .
Check if field exists in migration.
For me, I had put a . dot on my model. Like
protected $fillable = [
'department_id'.'name', 'email', 'password','username','role',
];
between department_id and name.
The spellings are also important. Since there is no data from the view, I can't say for sure - but check if everything is correct.

Laravel validation rules - optional, but validated if present

I'm trying to create a user update validation through form, where I pass, for example 'password'=>NULL, or 'password'=>'newone';
I'm trying to make it validate ONLY if it's passed as not null, and nothing, not even 'sometimes' works :/
I'm trying to validate as :
Validator::make(
['test' => null],
['test' => 'sometimes|required|min:6']
)->validate();
But it fails to validate.
Perhaps you were looking for 'nullable'?
'test'=> 'nullable|min:6'
Though the question is a bit old, this is how you should do it. You dont need to struggle so hard, with so much code, on something this simple.
You need to have both nullable and sometimes on the validation rule, like:
$this->validate($request, [
'username' => 'required|unique:login',
'password' => 'sometimes|nullable|between:8,20'
]);
The above will validate only if the field has some value, and ignore if there is none, or if it passes null. This works well.
Do not pass 'required' on validator
Validate like below
$this->validate($request, [
'username' => 'required|unique:login',
'password' => 'between:8,20'
]);
The above validator will accept password only if they are present but should be between 8 and 20
This is what I did in my use case
case 'update':
$rules = [
'protocol_id' => 'required',
'name' => 'required|max:30|unique:tenant.trackers'.',name,' . $id,
'ip'=>'required',
'imei' => 'max:30|unique:tenant.trackers'.',imei,' . $id,
'simcard_no' => 'between:8,15|unique:tenant.trackers'.',simcard_no,' . $id,
'data_retention_period'=>'required|integer'
];
break;
Here the tracker may or may not have sim card number , if present it will be 8 to 15 characters wrong
Update
if you still want to pass hardcoded 'NULL' value then add the
following in validator
$str='NULL';
$rules = [
password => 'required|not_in:'.$str,
];
I think you are looking for filled.
https://laravel.com/docs/5.4/validation#rule-filled
The relevant validation rules are:
required
sometimes
nullable
All have their uses and they can be checked here:
https://laravel.com/docs/5.8/validation#rule-required
if you want validation to always apply
https://laravel.com/docs/5.8/validation#conditionally-adding-rules
if you want to apply validation rules sometimes
https://laravel.com/docs/5.8/validation#a-note-on-optional-fields
if you want your attribute to allow for null as value too

Categories