Laravel 5 : Form Request based on conditional if - laravel

How I can apply conditional if in my rules() method in request something like this code.
public function rules()
{
if($request->field1 = 'something')
{
return [
'field1' => 'required',
'field2' => 'required',
];
}else if($request->field1 = 'other something')
{
return [
'field1' => 'required',
'field2' => 'required',
'field3' => 'required',
'field4' => 'required',
];
}
}

You can use request() helper function, it returns the current request instance or obtains an input item as:
public function rules()
{
if (request('field1') == 'something') {
return [
'field1' => 'required',
'field2' => 'required',
];
} else if (request('field1') == 'other something') {
return [
'field1' => 'required',
'field2' => 'required',
'field3' => 'required',
'field4' => 'required',
];
}
}

The FormRequest object is an instance of the Request, so just use $this to get the value you're looking for:
public function rules()
{
if ($this->field1 == 'something') {
return [
'field1' => 'required',
'field2' => 'required',
];
} else if ($this->field1 == 'other something') {
return [
'field1' => 'required',
'field2' => 'required',
'field3' => 'required',
'field4' => 'required',
];
}
}
Do note however that if field1 is not set to one of those two values (or is missing completely) the code above will not be returning any rules. You have to accomodate for that.

You can use Laravel Build-in Validation Rules Required If OR Required Unless OR Requred With in your case

Related

When use create() the fillable values come null

i have an array with values that i am trying to insert it in the database, but when i use create() the values are inserted as null in database while if i use insert() the values insert correct.
This is the code from the controller
public function store(Request $request)
{
$request->validate([
'order_number' => 'required',
'client' => 'required',
'products' => 'required',
'amount' => 'required',
'description' => 'required',
]);
for($i = 0; $i < count($request->products); $i++)
{
$values[] = [
'order_number' => $request->order_number,
'client' => $request->client,
'products' => $request->products[$i],
'amount' => $request->amount[$i],
'description' => $request->description
];
}
Order::create($values);
return redirect('/')->with('msg', 'Order Saved successfully!');
}
and this is the code from the model
public $timestamps = true;
protected $fillable = [
'order_number',
'client',
'products',
'amount',
'description',
];
The names are the same and in the database, any reason why the values come null when i use create() method?
insert() method accepts multiple objects in form of arrays to be created, for example :
DB::table('users')->insert([
['email' => 'picard#example.com', 'votes' => 0],
['email' => 'janeway#example.com', 'votes' => 0],
]);
But create() method does not accept such structure. You cannot create multiple entries using this method. So in this case you either keep using insert(), either move your create() inside for loop.
Edit : createMany() works only on relationships, and apparently DB manipulation in loops is antipattern. In that case you can do something like this :
$created_at = now();
for($i = 0; $i < count($request->products); $i++)
{
$values[] = [
'order_number' => $request->order_number,
'client' => $request->client,
'products' => $request->products[$i],
'amount' => $request->amount[$i],
'description' => $request->description,
'created_at' => $created_at,
'updated_at' => $created_at,
];
}
Order::insert($values);

Laraval array validation with unique email while update

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.');
}
}
}
},
],
];

How to validate array in Request rules laravel?

I create request in laravel for validation where i have to validate phone number array.How to validate it. Below i am sharing:
Array that i pass in postman is:
{
"name": "test nbame",
"phone_number": {
"number": "+8896 5432",
"internationalNumber": "+852 7896 5432",
"nationalNumber": "+8896 5432",
"e164Number": "+85278965432",
"countryCode": "HK",
"dialCode": "+852"
},
"designation": "xyz"
}
public function rules()
{
return [
'name' => 'required',
'dial_number' => 'required',
'phone_number' => 'required|regex:/(^[0-9 ]+$)+/',
//'image' => 'required',
];
}
how to validate phone_number array.
Based on your json you can do something like below
public function rules()
{
return [
'name' => 'required',
'dial_number' => 'required',
'phone_number' => 'required|array',
'phone_number.number' => 'required|regex:/(^[0-9 ]+$)+/',
'phone_number.internationalNumber' => 'required|regex:/(^[0-9 ]+$)+/',
'phone_number.nationalNumber' => 'required|regex:/(^[0-9 ]+$)+/',
'phone_number.e164Number' => 'required',
'phone_number.countryCode' => 'required|string',
'phone_number.countryCode' => 'required|string',
'phone_number.dialCode' => 'required',
//'image' => 'required',
];
}
for more info you can visit laravel documentation
You're validating against a nested array in Laravel:
public function rules()
{
return [
...
'phone_number.number' => 'required|regex:/(^[0-9 ]+$)+/',
];
}
Read more in the docs.
You will check the number by regex. You will find a lot of variants of possible phone numbers. That means that you need a regex which is very flexible. How flexible the regex should be depends on you. here is an example:
'phone_number.number' => 'required|regex:/(^[0-9 ]+$)+/',

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();
}

Laravel 5.4 Validation Request , How to handle unique validation on update?

I have a users table which has a unique validate rule on email and username. When i am trying to update not ignore unique validation. Please see my code below.
UserRequest.php
public function rules()
{
return [
'name' => 'required',
'mobile' => 'required',
'email' => 'required|unique:users,email'.$id,
'usercategory' => 'required',
'username' => 'required|unique:users,username'.$id,
];
}
Please try this
public function rules()
{
$id = $this->request->get('id') ? ',' . $this->request->get('id') : '';
return [
'name' => 'required',
'mobile' => 'required',
'email' => 'required|unique:users,email'.$id,
'usercategory' => 'required',
'username' => 'required|unique:users,username'.$id,
];
}
In laravel 5.5 you should do like this:
use Illuminate\Validation\Rule;
Validator::make($data, [
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
]);
Check laravel documentaion about rule-unique.
You needed to skip id if you validate for update, like as below
public function rules($id='')
{
$id = $id ? ','.$id.',id':'';
return [
'name' => 'required',
'mobile' => 'required',
'email' => 'required|unique:users,email'.$id,
'usercategory' => 'required',
'username' => 'required|unique:users,username'.$id,
];
}
In Laravel docs, you have provide 3rd and 4th param in unique rule
unique:table,column,except,idColumn
You could use something like this:
$id = $this->isMethod('put') ? ',' . auth()->id() : '';
assuming you use put method for update
before line with return
for somebody else faced this issue:
public function rules()
{
return [
'name' => 'required',
'mobile' => 'required',
'email' => 'required|unique:users,email'.$this->user->id,
'usercategory' => 'required',
'username' => 'required|unique:users,username'.$this->user->id,
];
}
I fixed this by using this:
public function rules()
{
$id = $this->user->id ?? null;
return [
"name" => "required",
"mobile" => "required",
"email" => "required|unique:users,email, $id",
"usercategory" => "required",
"username" => "required|unique:users,username, $id",
];
}
Note that for other models other than the User model, the user in $this->user->id will be the model name in lowercase

Resources