Laravel: Setting a Default Value for Blank/Null Input - laravel

This is the code in the migration:
$table->string('role')->default('Standard');
When I leave the input box blank, it gives me an error:
"SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'role' cannot be null
How do we set the default value to "Standard" if the input box is left blank?
Code for Controller
public function store(Request $request)
{
//return ['message' => 'I have your data'];
$request->validate([
'firstname' => 'required|string|max:191',
'lastname' => 'required|string|max:191',
'email' => 'required|string|email|max:191|unique:users',
'password' => 'required|string|min:6',
]);
return User::create([
'firstname' => $request['firstname'],
'lastname' => $request['lastname'],
'email' => $request['email'],
'phone' => $request['phone'],
'role' => $request['role'],
'usernotes' => $request['usernotes'],
'password' => Hash::make($request['password']), //make sure to import Hash: use Illuminate\Support\Facades\Hash;
'created_by' => $request['created_by'],
'updated_by' => $request['updated_by'],
]);
}

In your code $request['role'] should be null which is causing the problem since the role field is not Nullable.
What you can do is, add the dwfault value if the role is null, just made following changes in your code and it should work.
public function store(Request $request)
{
//return ['message' => 'I have your data'];
$request->validate([
'firstname' => 'required|string|max:191',
'lastname' => 'required|string|max:191',
'email' => 'required|string|email|max:191|unique:users',
'password' => 'required|string|min:6',
]);
return User::create([
'firstname' => $request['firstname'],
'lastname' => $request['lastname'],
'email' => $request['email'],
'phone' => $request['phone'],
'role' => $request['role'] ?? 'Standard',
'usernotes' => $request['usernotes'],
'password' => Hash::make($request['password']), //make sure to import Hash: use Illuminate\Support\Facades\Hash;
'created_by' => $request['created_by'],
'updated_by' => $request['updated_by'],
]);
}
That should fix the issue.
Explanation: I am using Null coalescing (??) operator of PHP which will replace the null value with 'Standard'. It works only is PHP 7+, if you have a lower version of PHP then you can consider using the Ternary operator(?:).
Reference: https://www.php.net/manual/en/migration70.new-features.php

use nullable();
$table->string('role')->default('Standard')->nullable();

Related

User create and update using updateOrCreate()

I am creating and updating user using below code.
public function store(Request $request)
{
if ($request->ajax()) {
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users,email,' .$request->user_id,
'password' => 'required',
'role' => 'required',
]);
$user = User::updateOrCreate(['id' => $request->user_id],
[
'name' => $request->name,
'email' => $request->email,
'role' => $request->role,
'password' => Hash::make($request->password)
]);
}
}
When I am updating record Password is updating also. How can I solve the issue ?
How validation is working here 'email' => 'required|email|unique:users,email,' .$request->user_id, when I am creating a record ? Because when I am creating a record at that time $request->user_id is not available.

parse_url() expects parameter 1 to be string, array given when creating user laravel

Im building my onw registration in laravel and when im trying to hash my password i get the error parse_url() expects parameter 1 to be string, array given
//Controller
HomeController.php
$filteredValidation = $request->except('_token');
$password = Hash::make($filteredValidation['password']);
UserRegistrationRequest::create([
'firstname' => $filteredValidation['firstname'],
'lastname' => $filteredValidation['lastname'],
'email' => $filteredValidation['email'],
'year' => $filteredValidation['year'],
'avatar' => $filteredValidation['firstname'],
'buddy' => $filteredValidation['firstname'],
'password' => $password,
]);
//request
UserRegistrationRequest.php
public function rules()
{
return [
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required',
'year' => 'required',
'password' => 'required',
];
}
I have no idea why this is happening

How to select data from multiple dropdown and combined them into one variable in laravel?

I have three dropdowns for Day, Month, and year for Date of Birth Data and one column dob in the database. I want to convert selected data into the date of birth format then stored in the database. this is creating syntax error.
my controller code :
protected function create(array $data)
{
'month' => $data['month'],
'day' => $data['day'],
'year' => $data['year'],
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'gender' =>$data['gender'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'phone' => $data['phone'],
'dob' => "month/day/year",
]);
}
$dob = $data['year'].'-'.$data['month'].'-'.$data['day'];
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'gender' =>$data['gender'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'phone' => $data['phone'],
'dob' => $dob,
]);

Validate Age Variable - Laravel RegisterController

I have added 3 fields to the Laravel OOB Registration Form, they are Birth Month, Day, and Year. I pass these fields to the validator function in the RegisterController and convert them to an age with Carbon:
$theAge = Carbon::createFromDate($data['birthyear'], $data['birthmonth'], $data['birthday'])->age;
This part works fine, I can pass the variable to a field in the table and see the correct age.
How do I add $theAge to my Validator?
return Validator::make($data, [
'email' => 'required|string|email|max:255|unique:users|confirmed',
'password' => 'required|string|min:8|confirmed',
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'address' => 'required|string|max:255',
'city' => 'required|string|max:255',
'state' => 'required|string|max:2',
'zipcode' => 'required|string|max:10',
'brand' => 'required',
'opt_in' => 'required',
'g-recaptcha-response' => 'required|captcha',
'birthmonth' => 'required',
'birthday' => 'required',
'birthyear' => 'required',
]);
I have tried the following but it appears to be ignored on validation:
$theAge => 'bail|min:21'
I have looked into the After Validation Hook but don't understand how to use it in my situation.
you can add the $theAge variable to the data array.
$data['age'] = Carbon::createFromDate($data['birthyear'], $data['birthmonth'], $data['birthday'])->age;
You can put the calculated value back in the $data before you call the validator like this:
$theAge = Carbon::createFromDate($data['birthyear'], $data['birthmonth'], $data['birthday'])->age;
$data['age'] = $theAge;
return Validator::make($data, [
'email' => 'required|string|email|max:255|unique:users|confirmed',
'password' => 'required|string|min:8|confirmed',
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'address' => 'required|string|max:255',
'city' => 'required|string|max:255',
'state' => 'required|string|max:2',
'zipcode' => 'required|string|max:10',
'brand' => 'required',
'opt_in' => 'required',
'g-recaptcha-response' => 'required|captcha',
'birthmonth' => 'required',
'birthday' => 'required',
'birthyear' => 'required',
'age' => 'min:21'
]);
Alternatively, you can let the user select their date of birth using date picker (e.g. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date) like this:
<input name="birthday" type="date">
and in your validator, do this define the age check plus a custom error message:
return Validator::make($data, [
// ... snipped
'birthday' => 'required|date|before_or_equal:' . Carbon::now()->subYears(21)->toDateString()
], [
'birthday.before_or_equal' => 'You must be at least 21 years old.'
]);

Laravel - Validate value against string

I am running some basic validation inside a Laravel 5.5 controller like this...
$this->validate($request, [
'name' => 'required|max:30',
'email' => 'required|unique:users|email',
'password' => 'required|max:20',
'mykey' => 'required',
]);
Is there a way to check if 'mykey' matches a php string I have saved? I know I can do an if statement and compare them but wondered if there was a way I could do this inside the validation itself?
You can use in rule, This works for n number of values
$request->validate([
'name' => 'required|max:30',
'email' => 'required|unique:users|email',
'password' => 'required|max:20',
'mykey' => [
Rule::in([env('MY_KEY'),config('app.another_key')]),
]
]);
Laravel provides a regex option for validation. Depending on the complexity of the string comparison it may be useful:
https://laravel.com/docs/5.5/validation#rule-regex
You can this rule:
$key = "my_saved_key"
$request->validate([
'name' => 'required|max:30',
'email' => 'required|unique:users|email',
'password' => 'required|max:20',
'mykey' => 'in:' . $key,
]
]);

Resources