Laravel unique validation with slug - php

I have two options, either the users gives a custom unique_id and I convert it via Str::slug($request->custom) or it gets generated via Str::random(6)
My code:
$post = new Post;
$unique_id = Str::random(6);
$idcustom = Str::slug($request->custom);
$this->validate($request, [
'custom' => 'max:25|string|unique:posts,unique_id' . Str::slug($post->unique_id),
]);
If the user creates the custom id, $idcustom gets inserted into the database, if he just leaves the field empty $unique_id gets inserted. But if there is already an entry with for example "stack overflow" I get an SQL error, that there is already an entry with that name, but if its like "stackoverflow" it works like it should. So it has to do with the slug, what am I doing wrong here?

I don't think you can put 'fallback' values into the validation rules. You'd perhaps want to check $request->custom manually before swapping it with your random string?
Not sure whether this'll help... your question is not clear on whether you're creating a new user or updating an existing one. If updating an existing one, don't forget to exclude from checking against the current user:
'custom' => ['max:25', 'string',
Rule::unique('users')->ignore($user->id)],

Related

Yii Confirm password before deleting model

my system (built in Yii 1.1.19), I have several instances where I delete a record, and I have a confirm request to bring an alert before it continues to delete - all works fine, see below;
$this->menu = array(
array('label' => 'Delete User', 'url' => '#', 'linkOptions' => array('submit' => array('delete', 'id' => $model->id), 'confirm' => "Are you sure you want to delete this user?",
'params' => array(Yii::app()->getRequest()->csrfTokenName => Yii::app()->getRequest()->csrfToken))),
);
Pretty standard Yii - however, I want the user to confirm their password before they delete specific records, as an extra security measure. Not necessarily within its own user model either, i.e. I might want to check the user's password before I delete a specific setting from a different model.
I understand what I need to do once I have an input - how to check the existing password, but I can't figure out how to actually alter the confirm to get the input form instead of standard confirm.
Can anyone help? Sounds like a straightforward request, but I can't seem to much online
Have you tried using "prompt" instead of confirm? or using a JS function and then calling prompt? https://www.w3schools.com/jsref/met_win_prompt.asp
That should allow you to get an input for the password. However, i don't think that's the best way since passwords are expected to be masked (prompt doesn't mask the input) so, what i would propose instead is to use an ajax loaded html form (could be modal) so you could properly handle the the password

validate all arrayitems except last in laravel

With the asterisk I can validate all array items, like this:
'event_time_start.*' => 'required|date_format:G:i',
But I want apply this validation rule on all items, except the last one. How can I achive this?
It is always recommended to exclude unnecessory item from front end if possible. If not you can remove last item before sending request data to Validator.
$requestData = $request->all();
$count = count($requestData["event_time_start"]);
unset($requestData["event_time_start"][$count-1]);
$validator = Validator::make( $requestData , [
'event_time_start.*' => 'required',
]);
In your JavaScript, you're cloning an empty hidden row when a user clicks add. My solution would be to not have a name attribute on that field, so it is never posted to the server. When you clone the row, then add the name="event_time_start[]" attribute to the newly cloned row.
This would preserve bandwidth and allow you to not need the squirrelly validator exception, which will be strange to read in code 6 months from now.

Sort "contact info" fields in Wordpress user profile

I can add and remove fields in the user profile section with:
function add_remove_contactmethods($contactmethods ) {
// Remove AIM
unset($contactmethods['aim']);
//add Phone
$contactmethods['phone'] = 'Phone';
return $contactmethods;
}
add_filter( 'user_contactmethods', 'add_remove_contactmethods' );
When I view this screen in the backend, the "Phone" field comes last, after some other fields like "Email" and "Website". I guess this is because my added field was added after the default Wordpress fields. How do I sort this, for instance alphabetically, so that my "Phone" field comes in alphabetical order instead of after the default fields? How do I sort the output of $contactmethods without messing it up?
try using ksort
function add_remove_contactmethods($contactmethods ) {
// Remove AIM
unset($contactmethods['aim']);
//add Phone
$contactmethods['phone'] = 'Phone';
ksort($contactmethods);
return $contactmethods;
}
add_filter( 'user_contactmethods', 'add_remove_contactmethods' );
re
UPDATE: So I guess the answer to my original question, is to explain why and how "Website" and "Email" are stored, and how the output is controlled in the backend when you view a profile. Maybe it's an ordered action? I guess "Website" and "Email" are just user meta, but how is the output order controlled. I accept that I might have to write a custom script to sort the output, I just don't know where to begin.
Your right about that, all the new contact fields were added into user_meta table. user_email and user_url are in the users table. The problem you are going to have doing this, is that a filter does not exist to modify the information. You can check the main filters here:
http://codex.wordpress.org/Plugin_API/Filter_Reference
and also you can look at core itself. All the admin templates are in wp-admin so you can look at the variable you need to modify in user-edit.php ($profileuser). Im in no way recommending this, but you could modify the template there, it will be overwritten on the next update of course so thats a drawback to it.
There may be a hook somewhere in admin in the load template process, if you could find one, you could relocate the template location to a theme file and recreate it with the changes you want. But all this seems like a lot of work to include just 2 fields to reorder?
Another approach is to use a higher priority the other when adding the fields. For example, Yoast adding 3 contact methods, and if you want your 'phone' appear before those, set the filter to:
add_filter('user_contactmethods', 'my_contactmethods', -5, 1);
Email and Website cant be re-ordered unless deep PHP coding or javascript re-order or advanced CSS.
if you know the key(s) (check the name fields in the source code), you can add other plugin fields by yourself, and choose exact appearance. A field is only added once if they added twice (!) This is how we use:
function entex_author_contactmethods($contactmethods){
$contactmethods['mail'] = __('Public email', 'entex-theme');
$contactmethods['phone'] = __('Phone', 'entex-theme');
$contactmethods['googleplus'] = __('Google+', 'wordpress-seo');
$contactmethods['youtube'] = __('YouTube URL', 'wordpress-seo');
$contactmethods['facebook'] = __('Facebook profile URL', 'wordpress-seo');
$contactmethods['instagram'] = __('Instagram URL', 'wordpress-seo');
$contactmethods['twitter'] = __('Twitter username (without #)', 'wordpress-seo');
$contactmethods['linkedin'] = __('LinkedIn URL', 'wordpress-seo');
$contactmethods['myspace'] = __('MySpace URL', 'wordpress-seo');
$contactmethods['pinterest'] = __('Pinterest URL', 'wordpress-seo');
return $contactmethods;
}
add_filter('user_contactmethods', 'entex_author_contactmethods', -5, 1);
Happy contact-ing!

DynamoDB PHP getItem() - How to tell if item does not exist

I am writing a "Get or Create" method that attempts to get an item, but if it doesn't exist, it will create a fresh new version of it. Obviously, I want to know for certain that the item didn't exist when I attempted to get it, so that it never overwrites existing data.
Am I correct in assuming $result["Item"] === null if and only if the item did not exist in the database at the time of the request? That is, if the item existed prior to the request, will this condition always evaluate to false, regardless of API errors, etc.? Or is there something else I should check for instead?
$result = $this->client->getItem(
array(
"TableName" => $tableName,
"Key" => array(
$keyName => array(Type::STRING => $key),
)
)
);
if ( $result["Item"] === null )
{
//Item does not exist; create it and write it to dynamoDb (code not shown)
}
return $result["Item"];
I would add 'ConsistentRead' => true in order to make sure your read is getting the absolute, most up-to-date data.
You are still going to have a potential race condition here where if multiple processes try to get the item and see that it is not there, then they will all try to write the item, but only one process won't have its data clobbered. As long as there is no chance that they will write different data, then it doesn't matter.
Consider a conditional put where you specify that the key must not exist before doing the put. This avoids any race condition, and takes only a single call. The only downside is that you must send the entire new item over the wire, even if it already exists.
Scroll down to the "specifying optional parameters" section here: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelJavaItemCRUD.html#PutLowLevelAPIJava
The code should look something like this:
// Optional parameters Expected and ReturnValue.
Map<String, ExpectedAttributeValue> expected = new HashMap<>();
expected.put(
"hashKeyAttributeName",
new ExpectedAttributeValue()
.withValue(new AttributeValue().withS("hashKeyValue"))
.withExists(false)
);

Content of form element not being saved to database while others are

I am working with a CMS like system, phpBMS, which defines a certain way of making forms, and defines the form elements to be used in such forms.
This is an example of the form template, and these are the fields that are defined.
Generally, it is pretty simple. If you have an inputField with the id of say, 'name', the content of that field will be saved to the name field in the table the form is assigned to.
Currently, I am using a different input field, inputSmartSearch, which works a bit like google suggest as it can search and automatically display results as you type.
I want to use the content of this field to go into a 'product' table, but I am unsure of how to set this up.
I am calling my smartsearch like so:
$theinput = new inputSmartSearch($db, "chooseproducts", "Choose Product",$therecord["product"], "Choose Product", TRUE, NULL, NULL, TRUE, $required=true);
$theinput->setAttribute("class","important");
$theform->addField($theinput);
When I look what is returned by _POST, I see:
Array ( [chooseproducts] => 75c72a6a-83d9-11df-951a-fa9c1ec271f2 [ds-chooseproducts] => Corona [quantity] => 2 [type] => cash)
I have setup the quantity and type fields like so
$theinput = new inputField("quantity",$therecord["quantity"],"Quantity",true, NULL, 1);
$theinput->setAttribute("class","important");
$theform->addField($theinput);
$theinput = new inputBasicList("type",$therecord["paymenttype"],array("Cash"=>"cash","Credit"=>"credit"), "Payment Type");
$theinput->setAttribute("class","important");
$theform->addField($theinput);
The content of the type and quanitity fields get insert into the database perfectly, but absolutely nothing gets inserted from the smartsearch field.
Why? How would I start to troubleshoot this?
I think in this case you would need to manually add this value to the array that is persisted to the database. So:
$variables["product"] = the value you want
So if you san. To persist the name assign Ds-chooseproducts. If you want to persist the id then use chooseproducts from the array.

Categories