How to apply a rule in laravel to check filename is unique? - laravel

In laravel 8 how can use the validation to check the file name provided in the array were unique.
` "main": [
{
"content": "ABC",
"filename": "recording_1",
"code": "264",
"parameters": ""
},
{
"content": "XYZ",
"filename": "recording_2",
"code": "264",
"parameters": ""
}
...more to come
]`
Above is the request structure. From that request, I have to check the all filename should be unique
How can I achieve this?

you can use distinct
$validator = Validator::make(
[
'main' =>
[
[
"content" => "ABC",
"filename" => "recording_1",
"code" => "264",
"parameters" => ""
],
[
"content" => "XYZ",
"filename" => "recording_1",
"code" => "264",
"parameters" => ""
]
]
],
['main.*.filename' => 'distinct']
);
then you can check
if($validator->fails()){
echo "<pre>";
print_r($validator->errors());
exit();
}
Output will be
Illuminate\Support\MessageBag Object
(
[messages:protected] => Array
(
[main.0.filename] => Array
(
[0] => The main.0.filename field has a duplicate value.
)
[main.1.filename] => Array
(
[0] => The main.1.filename field has a duplicate value.
)
)
[format:protected] => :message
)
Ref:https://laravel.com/docs/8.x/validation#rule-distinct

Related

How to replace specific item in a collection of items in Laravel

I have a bit of a problem in Laravel. I'm using a collection where I add in new users which have been registered to a particular activity. These are formatted in the following way
{
[
"ID" => "1",
"Email" => "test#example.com",
"Registrations" => [
"Sports" => [
[
"id" => "457",
"title" => "Football"
],
[
"id" => "459",
"title" => "Rugby"
]
]
]
],
[
"ID" => "2",
"Email" => "test2#example.com",
"Registrations" => [
"Sports" => [
[
"id" => "457",
"title" => "Football"
],
[
"id" => "458",
"title" => "Badminton"
]
]
]
]
}
The issue I'm having is that when attempting to add a new Sports id I'm not sure how to go about it. The way I originally thought about doing it is checking if that particular email has already been registered and then replacing the data within the collection. However I encountered a problem with each time there was an existing entry the whole data structure would get replaced. Any helpful advice? Below is a reference to what I already have
return $user_courses->where('ContactID' , $user['Registration']['Link']['Contact']['ContactID'])
->map(function($key) use ($user, $sportService){
$course_id = $sportService->validateSport($user['Registration']['Link']['Activity']['ContentUri']);
if($course_id){
$key['Registrations']['Sports'][] = [
'id' => $course_id,
'title' => $user['Registration']['Link']['Activity']['Title']
];
return $key;
}
return $key;
});
first, you can filter that object that you want to replace from the collection and then push the new object to it.
checkout this link

In Elasticsearch how can I get field length using the painless script?

I'm trying to update a field if it's longer than the existing one in an index, but neither of these function seem to work to get the length of a field
ctx._source.description.length() < params.description.length()
ctx._source.description.size() < params.description.size()
ctx._source.description.length < params.description.length
I get the same error that the methods don't exist. Any idea how to achieve this?
Edit:
This is the error I'm getting:
array:1 [
"update" => array:5 [
"_index" => "products_a"
"_type" => "_doc"
"_id" => "XjouMXoBeY37PI1TSOQl"
"status" => 400
"error" => array:3 [
"type" => "illegal_argument_exception"
"reason" => "failed to execute script"
"caused_by" => array:6 [
"type" => "script_exception"
"reason" => "runtime error"
"script_stack" => array:2 [
0 => """
if (ctx._source.description.length()<params.description.length()) {\n
\t\t\t\t\t\t\t\t
"""
1 => " ^---- HERE"
]
"script" => "add_new_seller_to_existing_doc"
"lang" => "painless"
"caused_by" => array:2 [
"type" => "illegal_argument_exception"
"reason" => "dynamic method [java.util.ArrayList, length/0] not found"
]
]
]
]
]
Edit 2:
Stored script
$params = [
'id' => 'add_new_seller_to_existing_doc',
'body' => [
'script' => [
'lang' => 'painless',
'source' =>
'if(params.containsKey(\'description\')){
if (!ctx._source.containsKey(\'description\')) {
ctx._source.description=params.description;
} else if (ctx._source.description.length()<params.description.length()) {
ctx._source.description=params.description;
}
}'
]
]
];
Bulk update command:
$bulk_obj['body'][] = ['update' => ['_id' => $id, '_index' => 'products']];
$bulk_obj['body'][] = ['id' => 'add_new_seller_to_existing_doc', 'params' => ['description'=>'some_description']];
The problem seems to be that the description field is an ArrayList awhile you think it is a String.
Either you use ArrayList.size() or you convert the ArrayList to a String (if it contains only one string) and you can then use String.length()

Proper way to Parse a Payload in Ruby

I have the following payload:
[{:payload=>
"{\"user\":\"test\",\"job\":\"Test\",\"username\":\"Bob\",\"blocks\":[{\"type\":\"section\",\"text\":{\"type\":\"mrkdwn\",\"text\":\"this is the title\"}},{\"type\":\"context\",\"elements\":[{\"type\":\"mrkdwn\",\"text\":\"Test\"}]},{\"type\":\"divider\"}]}"}]
I'm trying to figure out how to extract it. I tried
JSON.parse(response)
But I get the following error
TypeError: no implicit conversion of Hash into String
How can I extract this value to something where I can do something like:
response.job == "test" ?
Let's assume that you meant to say:
response = [{:payload => "{\"user\":\"test\",\"job\":\"Test\",\"username\":\"Bob\",\"blocks\":[{\"type\":\"section\",\"text\":{\"type\":\"mrkdwn\",\"text\":\"this is the title\"}},{\"type\":\"context\",\"elements\":[{\"type\":\"mrkdwn\",\"text\":\"Test\"}]},{\"type\":\"divider\"}]}"}]
Then response is an array with one element. That one element is a hash. You would thus access the payload with:
payload = JSON.parse(response.first[:payload])
=> {
"user" => "test",
"job" => "Test",
"username" => "Bob",
"blocks" => [
[0] {
"type" => "section",
"text" => {
"type" => "mrkdwn",
"text" => "this is the title"
}
},
[1] {
"type" => "context",
"elements" => [
[0] {
"type" => "mrkdwn",
"text" => "Test"
}
]
},
[2] {
"type" => "divider"
}
]
}
The payload object is then a hash and its child elements can be accessed using the standard [] call:
job = payload['job']
=> "Test"

How to write grok filter in logstash to accept variable arguments

How to write grok filter rule, if message contains transactions of variable arguments.
For example:
22-Jun-2015 04:45:56 Transaction for Bill 123 item1=100 item2=200 item3=300
22-Jun-2015 05:45:23 Transaction for Bill 124 item1=200
22-Jun-2015 06:23:36 Transaction for Bill 125 item4=400 item2=200 item1=100 item5=500
We can match date, time, bill # in the above case but how to handle for variable arguments item here.
Finally I was able to do that using kv{} option of logstash
For example:
item1=100&item2=200&item3=300
item1=100&item2=200&item3=300&item4=400
I created two messages and then I got the below output;
{
"message" => "item1=100&item2=200&item3=300",
"#version" => "1",
"#timestamp" => "2015-07-04T19:20:15.831Z",
"host" => "viswesn-PC",
"item1" => "100",
"item2" => "200",
"item3" => "300",
"tags" => [
[0] "true"
]
}
{
"message" => "item1=100&item2=200&item3=300&item4=400",
"#version" => "1",
"#timestamp" => "2015-07-04T19:20:25.866Z",
"host" => "viswesn-PC",
"item1" => "100",
"item2" => "200",
"item3" => "300",
"item4" => "400",
"tags" => [
[0] "true"
]
}

How do I access JSON array data?

I have the following array:
[ { "attributes": {
"id": "usdeur",
"code": 4
},
"name": "USD/EUR"
},
{ "attributes": {
"id": "eurgbp",
"code": 5
},
"name": "EUR/GBP"
}
]
How can I get both ids for futher processing as output?
I tried a lot but no success. My problem is I always get only one id as output:
Market.all.select.each do |market|
present market.id
end
Or:
Market.all.each{|attributes| present attributes[:id]}
which gives me only "eurgbp" as a result while I need both ids.
JSON#parse should help you with this
require 'json'
json = '[ { "attributes": {
"id": "usdeur",
"code": 4
},
"name": "USD/EUR"
},
{ "attributes": {
"id": "eurgbp",
"code": 5
},
"name": "EUR/GBP"
}]'
ids = JSON.parse(json).map{|hash| hash['attributes']['id'] }
#=> ["usdeur", "eurgbp"]
JSON#parse turns a jSON response into a Hash then just use standard Hash methods for access.
I'm going to assume that the data is JSON that you're parsing (with JSON.parse) into a Ruby Array of Hashes, which would look like this:
hashes = [ { "attributes" => { "id" => "usdeur", "code" => 4 },
"name" => "USD/EUR"
},
{ "attributes" => { "id" => "eurgbp", "code" => 5 },
"name" => "EUR/GBP"
} ]
If you wanted to get just the first "id" value, you'd do this:
first_hash = hashes[0]
first_hash_attributes = first_hash["attributes"]
p first_hash_attributes["id"]
# => "usdeur"
Or just:
p hashes[0]["attributes"]["id"]
# => "usdeur"
To get them all, you'll do this:
all_attributes = hashes.map {|hash| hash["attributes"] }
# => [ { "id" => "usdeur", "code" => 4 },
# { "id" => "eurgbp", "code" => 5 } ]
all_ids = all_attributes.map {|attrs| attrs["id"] }
# => [ "usdeur", "eurgbp" ]
Or just:
p hashes.map {|hash| hash["attributes"]["id"] }
# => [ "usdeur", "eurgbp" ]
JSON library what using Rails is very slowly...
I prefer to use:
gem 'oj'
from https://github.com/ohler55/oj
fast and simple! LET'S GO!

Resources