I want to check duplication value during insert time without using unique keyword - laravel-5.6

i make one table for with some column with nullable.
i already tried with two different query. one using
Register_member::where('passport',$passport)->orWhere('adharcardnumber',$adharcardnumber)->get();
and second DB::table type query.
$row = Register_member::where('passport',$passport)->orWhere('adharcardnumber',$adharcardnumber)->get();
if (!empty($row))
{
return response()->json(["status"=>0, "message"=>"Adharcard or Paasport number already exit."]);
}
if (empty($row))
{
Register_member::insert(['first_name'=>request('first_name'), 'middle_name'=>request('middle_name'), 'last_name'=>request('last_name'), 'adharcardnumber'=>request('adharcardnumber'), 'ocipcinumber'=>request('ocipcinumber'), 'passport'=>request('passport'), 'birthday'=>request('birthday'),
'mobilecode'=>request('mobilecode'), 'mobilenumber'=>request('mobilenumber'), 'email'=>request('email'), 'address'=>request('address'), 'landmark'=>request('landmark'), 'area'=>request('area'),
'gender'=>request('gender'), 'pincode'=>request('pincode'), 'city_name'=>request('city_name'), 'state_id'=>request('state_id'), 'country_id'=>request('country_id'), 'sampraday'=>request('sampraday'), 'other'=>request('other'), 'sms'=>request('sms')]);
return response()->json(["status"=>1, "message"=>"Member register successful."]);
}
if adharcardnumber or passport number are exists in table, then nagetive response. if in both any one in unique then, insert data in table

Let me suggest you something which I think serve you as a good solution. You can use the unique with required and regex. In this way it will use the already recommended ways of Laravel which are the best.
As an example for your adhaar card,
the validation should look like this
$request->validate([
'adhaar ' =>['required','unique:users','regex:/\d{12}/'],
]);
where adhar is the filed name where adhaar number is entered. Be sure to use validator like this use Illuminate\Support\Facades\Validator;. Also $request is the instance of the Request.
Using the required prevent empty field submission and the regex will throw an error if the pattern is not matched completely. so I think it would be a better a way to handle the scenario.
the above solution will work in both adhaar and passport. But for the passport the regex will be different though.
Please note these are all demo examples, you might need to modify it according to your needs. I use https://www.phpliveregex.com/ for regex making and checking and it is good enough.
I hope you get an idea of how to begin but if you need more information then let me know in the comments.

Related

put single row to variable and delete it at same time with one query

I have a password_resets table in mysql database and i want to get single raw of data and delete it with one query in Lumen with DB facade like this:
$reset_row = DB::table('password_resets')->where('token', $request->token)->first()->delete();
But i have a error :
Call to undefined method stdClass::delete()
i try this code :
$reset_row = DB::table('password_resets')->where('token', $request->token)
//do my work whith $reset_row->first();
$reset_row->delete();
But i think this way use 2 query to do this work.
NOTE : i know i can not delete and reason is first() method )return it to array)
Is there any way to do this?
Actually no need to use ->first(). Bcz your token is unique.
if you need try this.
$reset_row = DB::table('password_resets')->where('token', $request->token)
->Limit(1)->delete();
I think it is possible to use "limit" with "delete".
You can simply chain the delete method to your Query Buider.
No need to select the first on since you want to delete them, not select them.
DB::table('password_resets')->where('token', $request->token)->delete();
Its already answered in another post in StackOverflow.
You can use this answer too
laravel-delete-query-builder and you can also look at the official documentation about deleting using the query builder
At the end I Think to create model for reset password and Use it like this:
1. set primary key to token by set it on model like this
2. use find method to find token (document for find method)
use this way:
$reset=PasswordReset::find($token);
//work with $reset
$reset->delete()
NOTE: : for set primary key to string col see this link too

How to do string functions on a db table column?

I am trying to do string replace on entries of a column inside a db table. So far, I have reached till here:
$misa = DB::table('mis')->pluck('name');
for($i=0;;$i++)
{
$misa[$i] = substr_replace("$misa[$i]","",-3);
}
The error I am getting is "Undefined offset:443".
P.S. I am not a full-fledged programmer. Only trying to develop a few simple programs for my business. Thank You.
Since it's a collection, use the transform() collection method transform it and avoid this kind of errors. Also, you can just use str_before() method to transform each string:
$misa = DB::table('mis')->pluck('name');
$misa->transform(function($i) {
return str_before($i, ':ut');
});
There are a few ways to make this query prettier and FASTER! The beauty of Laravel is that we have the use of both Eloquent for pretty queries and then Collections to manage the data in a user friendly way. So, first lets clean up the query. You can instead use a DB::Raw select and do all of the string replacing in the query itself like so:
$misa = DB::table('mis')->select(DB::raw("REPLACE(name, ':ut' , '') as name"));
Now, we have a collection containing only the name column, and you've removed ':ut' in your specific case and simply replaced it with an empty string all within the MySQL query itself.
Surprise! That's it. No further php manipulation is required making this process much faster (will be noticeable in large data sets - trust me).
Cheers!

Propel having() with criteria

I add a virtual column, then I filter it using "having". When I need to filter by one value, all works fine, but I also need to filter by "not null". having expects only 3 arguments, including the clause, the value and the binding type, is there any way to pass in a criteria?
$Sharings->having("TotalSharing = ?",2, \PDO::PARAM_INT);
Or do I have to add a new virtual column who has as value what I need directly?
Thanks a lot in advance!
Gioia
Ok, was actually a lot easier then I thought, I just used:
$Sharings->having("TotalSharing > ?",0, \PDO::PARAM_INT);
So I didn't need to use a Criteria object, silly of me not to think about this, just so used to use filterBy...

Can you data-bind a composite id in Grails such that it (or parts of it) becomes updateable?

I am trying to read through the dataBind documentation, but it's not all that clear:
http://grails.org/doc/2.1.0/ref/Controllers/bindData.html
I have a composite id composed of 4 columns, and I need to update one of those. It refuses to .save() and doesn't even throw an error. Is there some configuration that will allow me to change these values and save the model?
If I delete it and create a new record, it will bump the rowid, which I was using on the browser side with datatables/jeditable, and it's not really an option. However, even if I include all the parameters with an empty list:
def a = WaiverExemption.find("from WaiverExemption as e where e.exemptionRowId = ?", [params.rowid])
a.properties = params
bindData(a, params, [include: []])
a.save(flush: true, failOnError: true)
This does not seem to work. I've also tried naming the columns/properties explicitly both by themselves and also with "id".
I was confused on what bindData() actually does. Still confused on that.
If you have a composite id in Grails and wish to change one or more of the column values, save() will never ever execute as suggested in the question. Instead, you'll want to use .executeUpdate(). You can pass in HQL that updates (though most of the examples on the web are for delete) the table in question, with syntax that is nearly identical to proper SQL. Something along the lines of "update domain d set d.propertyName = ?" should work.
I do not know if this is a wise thing to do, or if it violates some philosophical rule of how a Grails app should work, but it will actually do the update. I advise caution and plenty of testing. This crap's all voodoo to me.

blacklisting vs whitelisting in form's input filtering and validation

which is the preferred approach in sanitizing inputs coming from the user?
thank you!
I think whitelisting is the desired approach, however I never met a real whitelist HTML form validation. For example here is a symfony 1.x form with validation from the documentation:
class ContactForm extends sfForm
{
protected static $subjects = array('Subject A', 'Subject B', 'Subject C');
public function configure()
{
$this->setWidgets(array(
'name' => new sfWidgetFormInput(),
'email' => new sfWidgetFormInput(),
'subject' => new sfWidgetFormSelect(array('choices' => self::$subjects)),
'message' => new sfWidgetFormTextarea(),
));
$this->widgetSchema->setNameFormat('contact[%s]');
$this->setValidators(array(
'name' => new sfValidatorString(array('required' => false)),
'email' => new sfValidatorEmail(),
'subject' => new sfValidatorChoice(array('choices' => array_keys(self::$subjects))),
'message' => new sfValidatorString(array('min_length' => 4)),
));
}
}
What you cannot see, that it accepts new inputs without validation settings and it does not check the presence of inputs which are not registered in the form. So this is a blacklist input validation. By whitelist you would define an input validator first, and only after that bind an input field to that validator. By a blacklist approach like this, it is easy to forget to add a validator to an input, and it works perfectly without that, so you would not notice the vulnerability, only when it is too late...
A hypothetical whitelist approach would look like something like this:
class ContactController {
/**
* #input("name", type = "string", singleLine = true, required = false)
* #input("email", type = "email")
* #input("subject", type = "string", alternatives = ['Subject A', 'Subject B', 'Subject C'])
* #input("message", type = "string", range = [4,])
*/
public function post(Inputs $inputs){
//automatically validates inputs
//throws error when an input is not on the list
//throws error when an input has invalid value
}
}
/**
* #controller(ContactController)
* #method(post)
*/
class ContactForm extends sfFormX {
public function configure(InputsMeta $inputs)
{
//automatically binds the form to the input list of the #controller.#method
//throws error when the #controller.#method.#input is not defined for a widget
$this->addWidgets(
new sfWidgetFormInput($inputs->name),
new sfWidgetFormInput($inputs->email),
new sfWidgetFormSelect($inputs->subject),
new sfWidgetFormTextarea($inputs->message)
);
$this->widgetSchema->setNameFormat('contact[%s]');
}
}
The best approach is to either use stored procedures or parameterized queries. White listing is an additional technique that is ok to prevent any injections before they reach the server, but should not be used as your primary defense. Black listing is usually a bad idea because it's usually impossible to filter out all malicious inputs.
BTW, this answer is considering you mean sanitizing as in preventing sql injection.
WL is a best practice against BL whenever it is practicable.
The reason is simple: you can't be reasonably safe enumerating what it is not permitted, an attacker could always find a way you did not think about. If you can, say what is allowed for sure, it is simpler and much much safer !
Let me explain your question with few more question and answer.
Blacklist VS Whitelist restriction
i. A Blacklist XSS and SQL Injection handling verifies a desired input against a list of negative input's. Basically one would compile a list of all the negative or bad conditions, and verifies that the input received is not one among the bad or negative conditions.
ii. A Whitelist XSS and SQL Injection handling verifies a desired input against a list of possible correct input's. To do this one would compile a list of all the good/positive input values/conditions, and verifies that the input received is one among the correct conditions.
Which one is better to have?
i. An attacker will use any possible means to gain access to your application. This includes trying all sort of negative or bad conditions, various encoding methods, and appending malicious input data to valid data. Do you think you can think of every possible bad permutation that could occur?
ii. A Whitelist is the best way to validate input. You will know exacty what is desired and that there is not any bad types accepted. Typically the best way to create a whitelist is with the use of regular expression's. Using regular expressions is a great way to abstract the whitelisting, instead of manually listing every possible correct value.
Build a good regular expression. Just because you are using a regular expression does not mean bad input will not be accepted. Make sure you test your regular expression and that invalid input cannot be accepted by your regular expression.
Personally, I gauge the number of allowed or disallowed characters and go from there. If there are more allowed chars than disallowed, then blacklist. Else whitelist. I don't believe that there is any 'standard' that says you should do it one way or the other.
BTW, this answer is assuming you want to limit inputs into form fields such as phone numbers or names :) #posterBelow
As a general rule it's best to use whitelist validation since it's easier to accept only characters you know should go there, for example if you have a field where the user inputs his/her phone number you could just do a regex and check that the values received are only numbers, drop everything else and just store the numbers. Note that you should proceed to validate the resulting numbers as well. Blacklist validation is weaker because a skilled attacker could evade your validation functions or send values that your function did not expect, from OWASP "Sanitize with Blacklist":
Eliminate or translate characters (such as to HTML entities or to remove quotes) in an effort to make the input "safe". Like blacklists, this approach requires maintenance and is usually incomplete. As most fields have a particular grammar, it is simpler, faster, and more secure to simply validate a single correct positive test than to try to include complex and slow sanitization routines for all current and future attacks.
Realize that this validation is just a first front defense against attacks. For XSS you should always "Escape" your output so you can print any character's needed but they are escaped meaning that they are changed to their HTML entity and thus the browser knows it's data and not something that the parser should interpret thus effectively shutting down all XSS attacks. For SQL injections escape all data before storing it, try to never use dynamic queries as they are the easiest type of query to exploit. Try to use parameterized store procedures. Also remember to use connections relevant to what the connection has to do. If the connection only needs to read data, create a db account with only "Read" privileges this depends mostly on the roles of the users. For more information please check the links from where this information was extracted from:
Data Validation OWASP
Guide to SQL Injection OWASP
The answer generally is, it depends.
For inputs with clearly defined parameters (say the equivalent of a dropdown menu), I would whitelist the options and ignore anything that wasn't one of those.
For free-text inputs, it's significantly more difficult. I subscribe to the school of thought that you should just filter it as best you can so it's as safe as possible (escape HTML, etc). Some other suggestions would be to specifically disallow any invalid input - however, while this might protect against attacks, it might also affect usability for genuine users.
I think it's just a case of finding the blend that works for you. I can't think of any one solution that would work for all possibilities. Mostly it depends on your userbase.

Resources