Avoid duplication in doctor_id field with where clause in laravel 5.4 - laravel

this is my doctors id
this is my user id
I can't insert anything when I put unique in the validation of doctor_id. When there's no unique it works fine.
I want to avoid duplicate doctor_id where auth::id == 1. Any advice is appreciated.
public function store(Request $request, $id)
{
$auth = Auth::id();
$constraints = [
'doctor_id' => 'required|unique',
'day1' => 'required|max:20',
'day2'=> 'required|max:60',
'day3' => 'required|max:60'
];
$input = [
'users_id' => $auth,
'doctor_id' => $id,
'day1' => $request['day1'],
'day2' => $request['day2'],
'day3' => $request['day3'],
'day4' => $request['day4'],
...
'day27' => $request['day27'],
'status' => '1'
];
$this->validate($request, $constraints);
Itinerary::create($input);
$added = array('added'=> 'Added Doctor to Itinerary Successful!!');
return redirect()->back()->with($added);

Have you tried this? (assuming your table is named itineraries):
'doctor_id' => 'unique:itineraries'
According to Laravel Doc, you should add the table name, and column name if possible:
unique:table,column,except,idColumn

Related

laravel unique validation on foreign key

I have database table streets in which I am storing name and block_id as foreign key from the blocks table. So I want the name of street should be unique in every block. for example if the name of street is street 1 with block_id 1, it should not be added again with block_id 1 but it should be allowed to add street 1 with block_id 2 or 3. How can I get it with Laravel validation?
My validation Code:
here you can see I am validating uniqueness only on those records which have delete = false.
$validatedValues = $request->validate([
'block' => 'required',
'street' => [
'required',
Rule::unique('streets', 'sName')->where(function ($query) {
return $query->where('delete', false);
})
],
'street_width' => 'required',
]);
Replace this with street key in your code
'name' => [
'required',
Rule::unique('streets')->where(function ($query) use($request) {
return $query->where('name', $request->name)
->where('block_id', $request->block_id);
}),
],
try this one
Create request -> PHP artisan make:request StreetsRequest
in ur controller find the store method or whatever the name u put for storing ur data, and change the (Request $request) to (StreetsRequest $request)
use App\Http\Requests\StreetsRequest;
....
public function store(StreetsRequest $request){
$request->validated();
// Do whatever u want after validate
}
Open your StreetsRequest file and inside the return [] put sth like this
use Illuminate\Validation\Rule;
...
'block_id' => [
'required',
Rule::unique('streets','block_id')->ignore(request('id')),
],
i hope it will work , let us know if u still have any problem, thx
check laravel validation for more
[https://laravel.com/docs/8.x/validation#form-request-validation]
You can try writing custom validation for that
$validator = $request->validate([
'block' => 'required',
'street' => [
function ($attribute, $value, $fail) use($request){
$street= Street::where('delete', false)->where(function ($query)use($request){
$query->where('sName',$request->sName);
$query->where('block_id',$request->block_id );
})->exists();
if($street){
$fail('The '.$attribute.' is invalid.');
}
},
],
]);
I hope for streets table you have Street model
if any issue let me know .

How make a register form codeigniter with different database table

I tried to make a register form on a multiuser website with a different database table.
Eg when user1 registers, the data will be entered in table "user1",
when user2 registers, entered in table "user2".
I can only enter user1 and user2 into the same table.
This is my code using role_id
$data = [
'name' => htmlspecialchars($this->input->post('nama', true)),
'username' => htmlspecialchars($this->input->post('username', true)),
'photo' => 'default.jpg',
'password' => password_hash($this->input->post('password1'), PASSWORD_DEFAULT),
'role_id' => 2,
'is_active' => 1,
'is_date' => time()
];
You can do this by applying condition on role_id but this is only possible if there are only a number of users. If there are many users and you want to make a separate table for each one of them, try Database Forge Class(Bad practice)
I've written a possible solution for your question, comments are mentioned wherever necessary. See if it helps you.
Controller
$data = [
'name' => htmlspecialchars($this->input->post('nama', true)),
'username' => htmlspecialchars($this->input->post('username', true)),
'photo' => 'default.jpg',
'password' => password_hash($this->input->post('password1'), PASSWORD_DEFAULT),
'role_id' => 2,
'is_active' => 1,
'is_date' => time()
];
$this->xyz_model->xyz_function($data); // load xyz_model and call xyz_function with $data parameters
Xyz_model
function xyz_function($data){
$table = 'user1'; // default value
if($data['role_id'] != 1){ // other value is 2 -- assuming only 2 users are there(if not user if else or switch)
$table = 'user2';
}
$this->db->insert($table, $data);
return $this->db->insert_id();
}

Verify duplicate values (multi column unique) on the array in Laravel5.7

relate as below issue
Verify duplicate values on the array in Laravel5.7
I am add two fields to data base.
// database/migrations/UpdateUsersTable.php
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('staff_no' , 10);
$table->string('staff_code');
$table->unique(['staff_no', 'staff_code']);
});
}
I want to verify if multi column unique in my database or post array value is duplicate or not?
Here is my codes :
this is my Controller
UsersController
public function MassStore(MassStoreUserRequest $request)
{
$inputs = $request->get('users');
//mass store process
User::massStore($inputs);
return redirect()->route('admin.users.index');
}
and this is my POST data (post data($inputs) will send like as below) :
'users' => [
[
'name' => 'Ken Tse',
'email' => 'ken#gamil.com',
'password' => 'ken12ken34ken',
'staff_no' => '20191201CT',
'staff_code' => 'IT-1azz',
],
[
'name' => 'Tom Yeung',
'email' => 'tom#gamil.com',
'password' => 'tom2222gt',
'staff_no' => '20191201CT', // staff_no + staff_code is duplicate, so need trigger error
'staff_code' => 'IT-1azz',
],
]
MassStoreUserRequest
public function rules()
{
return [
'users' => ['required','array'],
'users.*.name' => ['required'],
'users.*.email' => ['required','unique:users','email', 'distinct'],
'users.*.password' => ['required','string','min:8'],
'users.*.staff_no' => ['required','size:10'],
'users.*.staff_code' => ['required','string']
// how to set verify duplicate values(staff_no,staff_code unique) in here?
];
}
You can use distinct validation rule. So your code will look like-
public function rules()
{
return [
'users' => ['required','array'],
'users.*.name' => ['required'],
'users.*.email' => ['required','unique:users','email', 'distinct'],
'users.*.password' => ['required','string','min:8'],
'users.*.staff_no' => ['required','size:10'],
'users.*.staff_code' => ['required','string', 'distinct']
];
}
Change
`'users.*.staff_code' => ['required','string']` line to
'users.*.staff_code' => ['required','string', Rule::exists('staff')->where(function ($query) {
//condition to check if staff_code and staff_no combination is unique
return $query->where('staff_code', $request->('your_key')['staff_code'])->where('staff_no', $request->('your_key')['staff_no']) ? false : true; // You may need to make a loop if you can not specify key
}),]
I solve this problem myself.
https://laravel.com/api/5.7/Illuminate/Foundation/Http/FormRequest.html#method_validationData
main point is overrides method validationData(),make value "staff_no_code" to validation data.
Here is my codes :
MassStoreUserRequest
public function rules()
{
$validate_func = function($attribute, $value, $fail) {
$user = User::where(DB::raw("CONCAT(staff_no,staff_code )", '=', $value))
->first();
if (!empty($user->id)) {
$fail(trans('validation.alreadyExists'));
}
};
return [
'users' => ['required','array'],
'users.*.name' => ['required'],
'users.*.email' => ['required','unique:users','email', 'distinct'],
'users.*.password' => ['required','string','min:8'],
'users.*.staff_no' => ['required','size:10'],
'users.*.staff_code' => ['required','string']
// 'distinct' check when working with arrays, the field under validation must not have any duplicate values.
// $validate_func check DB exist
'users.*.staff_no_code' => ['distinct',$validate_func]
];
}
//make value "staff_no_code" to validation data
protected function validationData()
{
$inputs = $this->input();
$datas = [];
foreach ($inputs as $input ) {
$input['staff_no_code'] = $input['staff_no'] . $input['staff_code'];
$datas[] = $input;
}
return $datas;
}

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
];

[cakePHP3]how to debug a failed save

This is my code , I have problems with making a simple save. The message is :( when i trying to save
$user = $this->Users->newEntity();
if($this->request->is('post'))
{
$user = $this->Users->patchEntity($user, $this->request->data);
if($this->Users->save($user))
{
$this->Flash->success(':)');
return $this->redirect(['controller' => 'Users', 'action' => 'index']);
}
else
{
$this->Flash->error(':(');
}
debug($this->request->data);
}
$this->set(compact('user'));
this is my table , I made a migration. All fields can be null
$table = $this->table('users');
$table->addColumn('first_name','string',array('limit'=>100))
->addColumn('last_name','string',array('limit'=>100))
->addColumn('email','string',array('limit'=>100))
->addColumn('password','string')
->addColumn('role','enum',array('values'=>'admin,user'))
->addColumn('active','boolean')
->addColumn('created','datetime')
->addColumn('modified','datetime')
->create();
this is my request data
[
'first_name' => 'wewe',
'last_name' => 'wewe',
'email' => 'wewe#wee.com',
'password' => 'wewewe',
'role' => 'admin',
'active' => '1'
]
I hope that you help me , I am very frustrated
EDIT: if i use print_r ($user->errors()); i get this...
Array ( [firts_name] => Array ( [_required] => This field is required ) )
Your error is in the name of your data, the request data is
'first_name' => 'wewe'"
your column name is "firts_name", its a typing error.

Resources