Laraval array validation with unique email while update - laravel

Updating form but email should be unique, request('contacts.*.id') is empty. It should have ID of that row. How can i get that ID?
return [
'email' => "required|email|unique:clients,email,".request('id'),
'client_type_text' => 'required',
'client_name' => 'required',
'phone_number' => 'required',
'contacts' => 'required|array',
'contacts.*.firstname' => 'required',
'contacts.*.lastname' => 'required',
'contacts.*.mobile' => 'required',
'contacts.*.email' => 'required|email|unique:users,email,'.request('contacts.*.id'),
];

It should work
return [
'email' => "required|email|unique:clients,email,".request('id'),
'client_type_text' => 'required',
'client_name' => 'required',
'phone_number' => 'required',
'contacts' => 'required|array',
'contacts.*.firstname' => 'required',
'contacts.*.lastname' => 'required',
'contacts.*.mobile' => 'required',
// check if email is unique for each contact id
'contacts.*.email' => [
'required',
'email',
function ($attribute, $value, $fail) {
$contact_id = explode('.', $attribute)[1];
$client_id = request('id');
$contact = \App\Models\Contact::where('id', $contact_id)->where('client_id', $client_id)->first();
if ($contact) {
$contact_email = $contact->email;
if ($contact_email != $value) {
$contact_with_email = \App\Models\Contact::where('email', $value)->first();
if ($contact_with_email) {
$fail('The email has already been taken.');
}
}
}
},
],
];

Related

How to create custom validation rule that only accepts specific numbers in Laravel?

How to set custom validation rule that accept only 1.00, 1.25, 1.50, 1.75, 2.00, 2.25, 2.50, 2.75 and 3.00 in input text? The grades and grades1 are my inputs.
1.35 should be invalid (incase you're thinking the solution of divisible by 5)
1.26 should be invalid
FormRequest
public function rules()
{
return [
'user_id' => 'required',
'app_id' => 'nullable',
'subjects.*' => 'required|string',
'subjects1.*' => 'required|string',
'school_year' => 'required',
'grades.*' => ['required','numeric','lt:2.50'],
'grades1.*' => 'required|lt:2.50',
'units.*' => 'required|integer|min:1',
'units1.*' => 'required|integer|min:1',
'term' => 'required',
'term1' => 'required',
'total.*' => 'nullable',
'total1.*' => 'nullable',
'gwa_1st' => 'required|lte:1.75',
'gwa_2nd' => 'required|lte:1.75',
'year_level' => 'required|string',
'image' => 'required|mimes:jpeg,png,jpg',
'award_applied' => 'required|string',
'course_id' => 'required|string'
];
}
Controller
public function store(AchieversAwardRequest $request)
{
$data = $request->validated();
$award = new StudentApplicants();
$award->user_id = $data['user_id'];
$award->school_year = $data['school_year'];
$award->gwa_1st = $data['gwa_1st'];
$award->gwa_2nd = $data['gwa_2nd'];
$award->year_level = $data['year_level'];
if ($request->hasfile('image')) {
$file = $request->file('image');
$filename = time() . '.' . $file->getClientOriginalExtension();
$file->move('uploads/', $filename);
$award->image = $filename;
}
$award->award_applied = $data['award_applied'];
$award->course_id = $data['course_id'];
$award->save();
$lastid = $award->id;
}
One possible solution would be to use the in validation rule, something like the following:
$acceptable = [1.00, 1.25, 1.5, 2.75, 3.00];
$validator = Validator::make(['numbers_field' => 2.75], [
'numbers_field' => [Rule::in($acceptable)]
]);
Update
Add the rule to your AchieversAwardRequest custom FormRequest rules() method along with all your other rules:
public function rules()
{
return [
'user_id' => 'required',
'app_id' => 'nullable',
'subjects.*' => 'required|string',
'subjects1.*' => 'required|string',
'school_year' => 'required',
'grades.*' => ['required','numeric','lt:2.50'],
'grades1.*' => 'required|lt:2.50',
'units.*' => 'required|integer|min:1',
'units1.*' => 'required|integer|min:1',
'term' => 'required',
'term1' => 'required',
'total.*' => 'nullable',
'total1.*' => 'nullable',
'gwa_1st' => 'required|lte:1.75',
'gwa_2nd' => 'required|lte:1.75',
'year_level' => 'required|string',
'image' => 'required|mimes:jpeg,png,jpg',
'award_applied' => 'required|string',
'course_id' => 'required|string'
'field_name' => [Rule::in([1.00, 1.25, 1.5, 2.75, 3.00])]
];
}
Obviously, replace field_name with the name of your input field. You will also need to include use Illuminate\Validation\Rule; at the top of your AchieversAwardRequest.

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

Validation fails even if it has values Maatwebsite Laravel Validation

I'm currently using Maatwebsite collection when processing the import CSV file and validating it as well since I'm having hard time using the ToModel way. Here's how I validate the csv fields:
class ImportRooms implements ToCollection, WithStartRow
{
public function collection(Collection $rows)
{
foreach($rows as $row){
\Validator::make($row->toArray(), [
'name' => $row[0],
'room_code' => $row[1],
'user_name' => $row[2],
'email' => $row[3],
'password' => $row[4],
'remarks' => $row[5],
'name' => ['required', 'max:50'],
'room_code' => ['required', 'max:50'],
'user_name' => ['required', 'max:255'],
'email' => ['required', 'email', 'max:255','nullable'],
'password' => ['min:8','max:255','nullable'],
'remarks' => ['max:500'],
])->validate();
}
}
/**
* #return int
*/
public function startRow(): int
{
return 2;
}
}
This is a sample data I have.
Illuminate\Support\Collection {#565 ▼
#items: array:6 [▼
0 => "Room name"
1 => "Room101"
2 => "user"
3 => "fmacejkovic#example.org"
4 => "password"
5 => "remarks"
]
}
My problem now is that even though the values are all correct and valid, it still fails in the validation. I'm trying to assign to a specific variable so that when it fails, it'll return the row name instead of row number. Even though I use the row number, it still fails.
You have used incorrect syntax for Validator::make(), use this :
class ImportRooms implements ToCollection, WithStartRow
{
public function collection(Collection $rows)
{
foreach($rows as $row){
$row = $row->toArray();
$data = [
'name' => $row[0],
'room_code' => $row[1],
'user_name' => $row[2],
'email' => $row[3],
'password' => $row[4],
'remarks' => $row[5],
];
\Validator::make($data, [
'name' => ['required', 'max:50'],
'room_code' => ['required', 'max:50'],
'user_name' => ['required', 'max:255'],
'email' => ['required', 'email', 'max:255','nullable'],
'password' => ['min:8','max:255','nullable'],
'remarks' => ['max:500'],
])->validate();
}
}
/**
* #return int
*/
public function startRow(): int
{
return 2;
}
}
Refer https://laravel.com/docs/5.8/validation#automatic-redirection
//Convert row data into array and store it in a variable.
$row = $row->toArray();
//Set data to be validated.
$data = [
'name' => $row[0],
'room_code' => $row[1],
'user_name' => $row[2],
'email' => $row[3],
'password' => $row[4],
'remarks' => $row[5]
];
//Set conditions for validation.
$conditions = [
'name' => 'required|max:50',
'room_code' => 'required|max:50',
'user_name' => 'required|max:255',
'email' => 'required|email|max:255|nullable',
'password' => 'min:8|max:255|nullable',
'remarks' => 'max:500'
];
//Validate the excel data.
\Validator::make($data, $conditions)->validate();

Laravel - syntax error, unexpected ''phone'' (T_CONSTANT_ENCAPSED_STRING), expecting ']'

I am using Laravel-5.8 as backend for an application. I have written all the Api for the endpoints.
Laravel: ApiController
$request->validate([
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email',
//'email' => 'required|email|unique:users|max:255',
'phone' => 'required|max:14',
'business_name' => 'required',
'truck_type' => 'required',
'truck_required' => 'required',
'quote_origin' => 'required',
'quote_destination' => 'required',
'commodity' => 'required',
// 'weight' => 'required',
'loading_date' => 'required'
]);
$clientquote = new ClientQuote([
'first_name' => $request->first_name,
'last_name'=> $request->last_name,
'email' => $request->email
'phone' => $request->phone,
'business_name' => $request->business_name,
'address' => $request->address,
'comment' => $request->comment,
'truck_type' => $request->truck_type,
'truck_required' => $request->truck_required,
'quote_origin' => $request->quote_origin,
'quote_destination' => $request->quote_destination,
'commodity' => $request->commodity,
'loading_date' => $request->loading_date
]);
$clientquote->save();
$mainData = array();
$mainData['to'] = $clientquote->toArray()['email'];
$mainData['from'] = "support#tsllimited.com";
$mainData['subject'] = "Client Quote";
$mainData['content'] = "Your Quote have been successfully received. You will hear from us shortly through the provided email. Thank you!";
$this->mailSend($mainData);
return response()->json([
'message' => 'Quote Successfully Sent!'
], 201);
}
public function indexClientQuote(Request $request) {
return response()->json(ClientQuote::get());
}
When I tested the Request on the POSTMAN, I got the error shown below:
I don't know why it's expecting ']'.
What could have caused the error?
you missed ',' after email
'email' => $request->email
'phone' => $request->phone,
To
$clientquote = new ClientQuote([
'first_name' => $request->first_name,
'last_name'=> $request->last_name,
'email' => $request->email, //here you missed comma
'phone' => $request->phone,
'business_name' => $request->business_name,
'address' => $request->address,
'comment' => $request->comment,
'truck_type' => $request->truck_type,
'truck_required' => $request->truck_required,
'quote_origin' => $request->quote_origin,
'quote_destination' => $request->quote_destination,
'commodity' => $request->commodity,
'loading_date' => $request->loading_date
]);

Data isn't inserting into different tables from one form

I'm trying to submit data from one form into two different tables, but it is not submitting, my form contains on two parts one is model, i.e., when modal form submit then its data saves into one table and rest of other data into another table.
Controller
public function store(Request $request)
{
$request->validate([
'patient_fname' => 'required',
'patient_lname' => 'required',
'patient_email' => 'required',
'patient_dob' => 'required',
'patient_guardian' => 'required',
'patient_gender' => 'required',
'user_id' => 'required',
'patient_name' => 'required',
'patient_insurance' => 'required',
'patient_insurance_id' => 'required',
'patient_reason' => 'required',
'patient_new' => 'required',
'patient_contact_no' => 'required',
'patient_message' => 'required',
]);
$userdata = Userdata::create([
Input::get('patient_fname'),
Input::get('patient_lname'),
Input::get('patient_email'),
Input::get('patient_dob'),
Input::get('patient_guardian'),
Input::get('patient_gender')
]);
$form = Form::create([
Input::get('patient_name'),
Input::get('patient_insurance'),
Input::get('patient_insurance_id'),
Input::get('patient_reason'),
Input::get('patient_new'),
Input::get('patient_contact_no'),
Input::get('patient_message')
]);
return back();
}
form.php
protected $guarded = [];
protected $table = "forms";
protected $fillable=['patient_name',
'patient_insurance','patient_insurance_id', 'patient_reason',
'patient_new', 'patient_message'];
public function userdata()
{
return $this->belongsTo('App\Userdata');
}
userdata.php
protected $fillable = ['patient_fname', 'patient_lname',
'patient_email', 'patient_dob', 'patient_guardian',
'patient_gender','user_id'];
public function form()
{
return $this->hasMany('App\Form');
}
I would imagine this is because you're not supplying a key for the values in your create method.
Also, validate will return an array of the validated properties so you can just use that instead of using Input::get():
public function store(Request $request)
{
$data = $request->validate([
'patient_fname' => 'required',
'patient_lname' => 'required',
'patient_email' => 'required',
'patient_dob' => 'required',
'patient_guardian' => 'required',
'patient_gender' => 'required',
'user_id' => 'required',
'patient_name' => 'required',
'patient_insurance' => 'required',
'patient_insurance_id' => 'required',
'patient_reason' => 'required',
'patient_new' => 'required',
'patient_contact_no' => 'required',
'patient_message' => 'required',
]);
$userdata = Userdata::create([
'patient_fname' => $data['patient_fname'],
'patient_lname' => $data['patient_lname'],
'patient_email' => $data['patient_email'],
'patient_dob' => $data['patient_dob'],
'patient_guardian' => $data['patient_guardian'],
'patient_gender' => $data['patient_gender'],
]);
$form = Form::create([
'patient_name' => $data['patient_name'],
'patient_insurance' => $data['patient_insurance'],
'patient_insurance_id' => $data['patient_insurance_id'],
'patient_reason' => $data['patient_reason'],
'patient_new' => $data['patient_new'],
'patient_contact_no' => $data['patient_contact_no'],
'patient_message' => $data['patient_message'],
]);
return back();
}

Resources