How to use Rule:unique with array of values compared to another column in laravel? - laravel

i have a request for array of values and i validate it with the following code
$request->validate([
'doctor_id.*' => ['required'],
'doctor_id' => [Rule::unique('project_orders')->where(function ($query) use ($student) {
$query->where('student_id', $student->id);
})],
]);
but the unique validation doesn't work and the data was inserted to the table with duplication
i want the doctor_id field to be unique with the student_id column, what should be the correct rule?
any help please ?

First you need to do validation on database level, so you will add in your migration
$table->unique(['doctor_id', 'student_id']);
This will make sure that there will be no duplication for same doctor_id and student_id values
Then in your validation layer you will add
$request->validate([
'doctor_id.*' => 'unique:project_orders,doctor_id,NULL,id,student_id,'.$student->id,
]);

You can do the validation like this
$request->validate([
'doctor_id.*' => [ Rule::unique('project_orders', 'doctor_id')->where('student_id', $student->id) ]
]);

Related

Validation check if requested value exists in another table Laravel 9

Hello i am trying to make a validation that checks the inserted values if they exist or not in other tables. This is the code i have done now:
$request->validate([
'order_number' => 'required',
'client_id' => 'required,exists:clients',
'description' => 'required',
]);
These values are inserted in a table called order but the client_id is taken from another table called clients and i want to verify if the value of client_id exists in the row id of the table clients
Please check here
Laravel Validation
As mentioned in laravel document you need to specify a column name, because if you don't, it will use the key in the request for the column name, so in your example, it will be the clients table and client_id column but you need to specify the column name in exists rule, it will be something like this:
$request->validate([
'order_number' => 'required',
'client_id' => 'required|exists:clients,id',
'description' => 'required',
]);
Also, you used the wrong syntax for separating rules, after required you need to use a pipe(|) to separate your rules and use multiple validations.

How to prevent duplicates in Laravel Eloquent?

I want to transform my database entry creation inside NewsletterController.php:
$email = $request->input('email');
$table = DB::table('newsletters');
$table->insert(array('email' => $email, 'created_at' => now()));
to prevent duplicate entries. I tried doing this:
$table = DB::updateOrCreate('newsletters');
but this method does not seem to exist for DB. How would I do that?
when you may want to update an existing record in the database or create it if no matching record exists. In this scenario, the updateOrInsert method may be used. The updateOrInsert method accepts two arguments: an array of conditions by which to find the record, and an array of column and value pairs indicating the columns to be updated.
The updateOrInsert method will attempt to locate a matching database record using the first argument's column and value pairs. If the record exists, it will be updated with the values in the second argument. If the record can not be found, a new record will be inserted with the merged attributes of both arguments
DB::updateOrInsert(['email'=>$eamil],['created_at'=>Carbon::now()]);
now, if email exists, the 'created_at' will be updated, otherwise a new row will be inserted with values of the merged array arguments
updateOrCreate you use for Eloquent Builder and updateOrInsert you use for Query Builder. Try with updateOrInsert.
$table = DB::updateOrInsert->table('newsletters')->([ 'id' => $request->id ], [
'email' => $email,
]);
Thanks to Moussab Kbeisy's comment I can validate for uniqueness which will return a 422 error if not met instead of inserting into the database:
$this->validate($request, [
'email' => 'required | unique:newsletters'
]);
$email = $request->input('email');
$table = DB::table('newsletters');
$table->insert(['email' => $email, 'created_at' => now()]);

Laravel send mail with multiple check box value

i'm trying to make inquiry form where costumer fill up form then check the value on the checkbox then once they submit form will send email to me listing all the information the customer selected, now problem is i want to change this[event_id,requirement_id] instead of id replace it with name those two id parameter is from my two model listed below.
Model:
Event:[id,name]
Requirement:[id,name]
Controller:
public function store(Request $request)
{
$summary=[
'name' => $request->fullname,
'email' => $request->email,
'company' => $request->company,
'event' => $request->event_id,
'requirement' => $request->requirement_id
];
return $summary;
Mail::send('emails.contact-message',[
],function($mail) use($summary){
$mail->from('myemail#gmail.com', 'tester');
$mail->to('myemail#gmail.com')->subject('Contact Message');
});
return redirect()->back();
}
This is the result of my return request:
{"name":"myname","email":"myemail#gmail.com","company":"mycompany","event":["1","2"],"requirement":["1","2"]}
As you can see the array Event has value of 1 and 2 i wanted to replace it with its name output should be [Wedding,Birthday] i'm sorry for my bad english hope you understand me..
Well, you'd need to pull the name from your models.
The following should do the trick:
$events = App\Event::whereIn('id', $request->event_id)
->get()
->pluck('name')
->toArray();
$requirements = App\Requirement::whereIn('id', $request->requirement_id)
->get()
->pluck('name')
->toArray();
Obviously, replace name in the above example with the actual name field in your models. This is just an example.
$events and $requirements will both be an array containing the names matching the ids you are supplying in your request.
You also need to change your $summary array as follows:
$summary = [
'name' => $request->fullname,
'email' => $request->email,
'company' => $request->company,
'event' => $events
'requirement' => $requirements
];

updateOrCreate isn't filling all the fields in Laravel 5.6

I have a code:-
$tokenUpdated = AppToken::updateOrCreate(
array(
'user_id' => $user_id, 'token' => $token),
array('expiry'=>$expiryTime,
'created_date'=>$created_at,
'modified_date'=>$created_at)
);
Though new rows are being inserted, the expiry, created_date fields values aren't getting saved. They records show NULL value which are default values.
What am I doing wrong?
First you need to check if expiry and created_date are returning values, if so then you could use the updateOrCreate function like this:
$tokenUpdated = AppToken::updateOrCreate(
['user_id' => $user_id, 'token' => $token]
['expiry'=>$expiryTime,
'created_date'=>$created_at,
'modified_date'=>$created_at
]
);
check laravel eloquent documentation: https://laravel.com/docs/5.6/eloquent

Laravel - exclude current email from unique validation

I am trying to use unique on an email address in Laravel 5.5 validation like this..
$rules = [
'email' => 'email|unique:users,email,
];
This is working and is checking the 'users' table in the 'email' column
But if the email address is the same as the currently saved one then this also fails validation.
Is there a way I can add an exception rule to the validation to ignore $user-email?
The unique rule takes a third parameter: a record to ignore, see "Forcing A Unique Rule To Ignore A Given ID".
Pass in the ID of the record you do not wish to be included in the unique test, e.g:
$rules = [
'email' => 'email|unique:users,email,' . $user->id
];
THIS IS AN EASY SOLUTION
Just add $this->route('id') as the third parameter
if your route was defined like this:
Route::put('{company}', 'CompanyController#update')
->name('update');
then your parameter name is "company"
So in your FormRequest:
public function rules()
{
$rules = [
'url' => [
'required',
'url',
'unique:companies,url,'.$this->route('company') ?? 0
],
];
// dd($rules); << check yourself
return $rules;
}
This FormRequest works the same for insert or update.
this line will instruct to ignore "0" in case of insert
$this->route('company') ?? 0

Resources