eloquent collection - unique field on relationship - collections

I have a User model and a Team model, and there can be many users (belongsToMany relatioship) in a Team. What I need now is to extract a list of all users from the teams that the logged in user is a member of.
I have below code currently:
$teams = $user->teams()->get()->pluck('id')->toArray();
return Team::whereIn('id', $teams)->with(['users'])->get()->map(function ($item) {
return $item->users->map(function ($user) {
return [
'name' => $user->name,
'email' => $user->email,
];
});
});
Above returns a collection, similar to below:
Collection {#375 ▼
#items: array:2 [▼
0 => array:3 [▼
0 => array:2 [▼
"name" => "John Doe",
"email" => "john.doe#mail.com"
]
1 => array:2 [▼
"name" => "Jane Doe",
"email" => "jane.doe#mail.com"
]
2 => array:2 [▶]
]
1 => array:2 [▼
0 => array:2 [▼
"name" => "Jane Doe"
"email" => "jane.doe#mail.com"
]
1 => array:2 [▼
"name" => "John Doe",
"email" => "john.doe#mail.com"
]
]
]
}
Here's a better view:
[
[
{
"name": "John Doe",
"email": "john.doe#mail.com"
},
{
"name": "Jane Doe",
"email": "jane.doe#mail.com"
},
{
"name": "John Doe",
"email": "john.doe#mail.com"
}
],
[
{
"name": "Jane Doe",
"email": "jane.doe#mail.com"
},
{
"name": "John Doe",
"email": "john.doe#mail.com"
}
]
]
As you can see I have duplicates, I need to get rid of those. I've tried using distinct and unique without success.

I partly solved it by using a foreach loop, but would prefer if I could get this data using the eloquent query.
$userArray = array();
foreach ($users as $user) {
if (array($user)) {
foreach ($user as $u) {
$userArray[] = $u['email'];
}
} else {
$userArray[] = $user['email'];
}
}
return array_unique($userArray);

Related

GA4 Api - How to filter metrics with php library

I am trying to filter dimensions with the GA4 api php library. Unfortunately, it is still in beta and I can't find any php examples on how to filter dimensions.
My code returns "Expect Google\Analytics\Data\V1beta\NumericValue."
Any help would be appreciated.
$response = $client->runReport([
'property' => 'properties/' . $property_id,
'dateRanges' => [
new DateRange([
'start_date' => 'yesterday',
'end_date' => 'yesterday',
]),
],
'dimensions' => [
new Dimension([
'name' => 'eventName',
]),
],
'metrics' => [new Metric(
[
'name' => 'eventCount',
])
],
'metricFilter' => new FilterExpression([
'filter' => new Filter([
'field_name' => 'eventCount',
'numeric_filter' => new Filter\NumericFilter([
'operation' => Filter\NumericFilter\Operation::GREATER_THAN,
'value' => '10000',
])
]),
]),
]);
Here is the JSON version of the request from the api explorer:
{
"dimensions": [
{
"name": "eventName"
}
],
"metrics": [
{
"name": "eventCount"
}
],
"dateRanges": [
{
"startDate": "yesterday",
"endDate": "yesterday"
}
],
"metricFilter": {
"filter": {
"fieldName": "eventCount",
"numericFilter": {
"operation": "GREATER_THAN",
"value": {
"int64Value": "10000"
}
}
}
}
}
I found the solution, I decided to leave this post since there is very little out there about filtering the ga4 api.
'metricFilter' => new FilterExpression([
'filter' => new Filter([
'field_name' => 'eventCount',
'numeric_filter' => new Filter\NumericFilter([
'operation' => Filter\NumericFilter\Operation::GREATER_THAN,
'value' => new NumericValue([
'int64_value' => '10000'
]),
])
]),
]),
```

WordPress rest api custom endpoint not getting all meta data, getting some fields meta data only

In the WordPress website, I have added one custom post type "inventory".To post data to that inventory created one end rest API endpoint. the created endpoint is not getting all the metadata from the inventory post type. In that inventory post type, I have an input field to enter date but while getting the data using endpoint I am not getting that date field data. I have tried register_rest_field() to get metadata using API endpoint, but in postman, I am getting only some fields.
My HTML Code looks like below
<div class="from_date inventory-form-to-input">
<input type="text" style="border: 1px solid #ddd;" class="pac-date-picker hasDatepicker"
name="nets_availability_pickup_datetime[]" value="0000-00-00 00:00:00" autocomplete="off"
id="dp1605714040849">
</div>
<div class="to_date inventory-form-to-input">
<input type="text" style="border: 1px solid #ddd;" class="pac-date-picker hasDatepicker"
name="nets_availability_dropoff_datetime[]" value="0000-00-00 00:00:00" autocomplete="off"
id="dp1605714040850">
</div>
And response in postman:
{
"id": 197794,
"date": "2020-11-03T04:33:35",
"date_gmt": "2020-11-03T10:33:35",
"guid": {
"rendered": "https://mywebsite.com.com/?post_type=inventory&p=197794"
},
"modified": "2020-11-17T10:11:24",
"modified_gmt": "2020-11-17T16:11:24",
"slug": "000-030-065x-001",
"status": "publish",
"type": "inventory",
"link": "https://mywebsite.com.com/inventory/000-030-065x-001/",
"title": {
"rendered": "000-030-065x-001"
},
"featured_media": 0,
"parent": 0,
"template": "",
"meta": {
"nets_hourly_ranges_cost": [
"a:0:{}"
],
"nets_daily_pricing": [
"a:0:{}"
],
"nets_monthly_pricing": [
"a:0:{}"
],
"nets_day_ranges_cost": [
"a:0:{}"
],
"_edit_lock": [
"1605629551:619"
],
"_edit_last": [
"619"
],
"quantity": [
"1"
],
"pricing_type": [
"general_pricing"
],
"general_price": [
"100"
],
"_yoast_wpseo_focuskeywords": [
"[]"
],
"_yoast_wpseo_keywordsynonyms": [
"[\"\"]"
]
},
"quantity": "1",
"pricing_type": "general_pricing",
"general_price": "100",
"nets_availability_block_by": [],
"nets_availability_pickup_datetime": "",
"_links": {
"self": [
{
"href": "https://mywebsite.com.com/wp-json/wp/v2/inventory/197794"
}
],
"collection": [
{
"href": "https://mywebsite.com/wp-json/wp/v2/inventory"
}
],
"about": [
{
"href": "https://mywebsite.com/wp-json/wp/v2/types/inventory"
}
],
"wp:attachment": [
{
"href": "https://mywebsite.com/wp-json/wp/v2/media?parent=197794"
}
],
"curies": [
{
"name": "wp",
"href": "https://api.w.org/{rel}",
"templated": true
}
]
}
},
tried below code to create a custom endpoint and to get metadata:
function my_plugin_rest_route_for_post( $route, $post ) {
if ( $post->post_type === 'inventory' ) {
$route = '/wp/v2/inventory/' . $post->ID;
}
return $route;
}
add_action( 'rest_api_init', function () {
register_rest_field( 'inventory', 'quantity', array(
'get_callback' => function( $post_arr ) {
return get_post_meta( $post_arr['id'], 'quantity', true );
},
) );
register_rest_field( 'inventory', 'pricing_type', array(
'get_callback' => function( $post_arr ) {
return get_post_meta( $post_arr['id'], 'pricing_type', true );
},
) );
register_rest_field( 'inventory', 'general_price', array(
'get_callback' => function( $post_arr ) {
return get_post_meta( $post_arr['id'], 'general_price', true );
},
) );
register_rest_field( 'inventory', 'nets_availability_block_by', array(
'get_callback' => function( $post_arr ) {
return get_post_meta( $post_arr['id'], 'nets_availability_block_by',false);
},
) );
register_rest_field( 'inventory', 'nets_availability_pickup_datetime', array(
'get_callback' => function( $post_arr ) {
return get_post_meta( $post_arr['id'], 'nets_availability_pickup_datetime', true );
},
) );
/*used to get all metadata*/
register_rest_field( 'inventory', 'meta', array(
'get_callback' => function( $post_arr ) {
return get_post_meta( $post_arr['id'], '', true );
},
) );
} );
please anyone suggest me how to get those datefields 'nets_availability_pickup_datetime' & 'nets_availability_dropoff_datetime'.
Thanks in advance.
You can get inspiration from one of my old code. Permission callback is used to add a security layer to your API, but is usually optional. The parameter args is also optional.
register_rest_route('v2/boutique', '/order/status', array(
'methods' => 'POST',
'permission_callback' => array($this, 'check_access'),
'callback' => array($this, "api_check_order"),
'args' => [
'transaction_id', 'order_id'
],
));
public function check_access(WP_REST_Request $request)
{
// Check credential
// if(in_array($_SERVER['REMOTE_ADDR'], self::$available_ip)){
$creds = $request->get_header('token');
if (!empty($creds)) {
if (self::verify_token(self::$creds_pass, $creds)) {
return true;
} else {
return new WP_Error(
'rest_forbidden',
__('Error'),
array('status' => 404)
);
}
} else {
return new WP_Error(
'rest_forbidden',
__('Error'),
array('status' => 404)
);
}
}

FacetWP, query from today's date

i'm looking for a way to query posts with a date from today (current day).
My query looks like that :
<?php
return [
"post_type" => [
"event"
],
"post_status" => [
"publish"
],
"meta_query" => [
"0" => [
"key" => "date",
"compare" => ">",
"type" => "DECIMAL(16,4)",
"value" => "XXXXX"
],
"sort_0" => [
"key" => "date",
"type" => "CHAR"
]
],
"orderby" => [
"sort_0" => "ASC"
],
"posts_per_page" => "4"
];
I don't know what to set on TYPE and VALUE.
Is this possible to help me please?
Thanks a lot.
Actually I found out how to do it :)
Here is the snippet I should have used :
<?php
return [
"post_type" => [
"event"
],
"post_status" => [
"publish"
],
"meta_query" => [
"sort_0" => [
"key" => "date",
"compare" => ">",
"type" => "DATE",
"value" => date("Y-m-d"),
]
],
"orderby" => [
"sort_0" => "ASC"
],
"posts_per_page" => "4"
];

Symfony 4.1 - Validate one field to check if email or phone number

I use Symfony 4.1 and I want to valid one field, name's identifier, it can take an email or one phone number.
So I want valid if field is an email, or if field is a phone number.
$constraint = new Assert\Collection([
'op' => new Assert\Required([
new Assert\Choice(['choices' => Operators::toArray()]),
]),
'value' => [
new Assert\Required([
new Assert\Collection([
'identifier' => [
new Assert\Email(),
],
]),
]),
],
]);
return $this->validator->validate($data, $constraint);
The body I send is:
[
{
"op": "add",
"value": {
"identifier": "john.doe#example.com",
"identifierType": "email"
}
},
{
"op": "add",
"value": {
"identifier": "+33600000000",
"identifierType": "phone"
}
}
]

How to use match_phrase with constant_score, terms

This is my query in symfony2. I want to add here "match_phrase", but anywhere i add that, I get errors.
$params = [
'index' => 'articles_v2',
'type' => 'article',
'body' => [
"sort" => [
[ "date" =>
["order" => "desc"]
],
],
"from" => $fromId,
"size" => $newsPerPage,
"query" => [
"constant_score" => [
"filter" => [
"bool" => [
"must" => [
["terms" => [ "article.topics" => $topics ] ],
["match_phrase" => ["article.bodytext" => [$search_phrase] ]]
]
]
]
]
]
]
];
$response = $client->search($params);
When I try to run this, I get error:
nested: QueryParsingException[[articles_v2] No filter registered for [match_phrase]]; }]","status":400
So where to place this match_phrase?
(I want to get results like SQL LIKE '%xxxx%')
I have changed the query. this time no errors, but anyway, no filtration.
$params = [
'index' => 'articles_v2',
'type' => 'article',
'body' => [
"sort" => [
[ "date" =>
["order" => "desc"]
],
],
"from" => $fromId,
"size" => $newsPerPage,
"query" => [
"constant_score" => [
"filter" => [
"bool" => [
"must" => [
["terms" => [ "article.topics" => $topics ] ]
]
]
],
"query" => [
"multi_match" => [
"query" => $search_phrase,
"fields" => [ "title", "bodytext" ]
]
]
]
]
]
];
$response = $client->search($params);
The solution is not to use match with constant score.
You have to use query/bool/must and all this match and other conditions inside must.
Here is the code.
$params = [
'index' => 'articles_v2',
'type' => 'article',
'size' => 50,
'body' => [
"sort" => [
[ "date" =>
["order" => "desc"]
],
],
"from" => $fromId,
"size" => $newsPerPage,
"query" => [
"bool" => [
"must" => [
[
"match_phrase_prefix" => [
"_all" => [
"query" => $search_phrase,
"operator" => "and",
"analyzer" => "analyzer_cs"
]
]
],
["terms" => [ "article.topics" => $topics ] ],
["range" => [ "article.date" => [ "from" => $date_from,"to" => $date_till]]]
]
]
]
]
];

Resources