Using Laravel's pluck method without an associative array - php

Let's say I've got an Articles collection, and I want to fetch the popular articles.
So first, I make a scopePopular() method in the Article method. Very simple.
Now I want to fetch their ids, so I'll do this:
Article::popular->pluck('id');
The result will be an associative array:
[
0 => 1,
1 => 34,
2 => 17
...
];
I want to get a normal array, without the keys, Like:
[1, 34, 17]
I know I can just do something like this:
array_values(Article::popular->pluck('id'));
But I believe Laravel has much more cleaner way to do this. Any ideas?

All arrays have indexes.
[
0 => 1,
1 => 34,
2 => 17
];
equals to
[1, 34, 17]
In other words:
$a1 = [0 => 1, 1 => 34, 2 => 17];
$a2 = [1, 34, 17];
$a1 === $a2;
// returns True

You can use values() method which is wrapper for array_values():
Article::popular->pluck('id')->values();

Its exactly what you need and what you get, By default php has the incremental key from 0.
You want to see something like a JSON array I assume.
Just do a return the array and you will see the JSOn array in browser, but internally its like this only.
Please confirm and let me know.Thanks

$store_type = \App\Websites::find($request->store_id)->first()->store_type;
// Outputs - just a string like "live" // there was option like a demo, live, staging ...
It might be useful for someone else.

Related

PHP pack with multiple values with different lengths

I'd like to pack a string consisting of a 64 bits, 32 bits and 32 bits ints.
I don't have much experience with the pack function (or bits altogether) so I'm trying to do something like this:
pack('JNN', 1, 2, 3);
// and
unpack('JNN');
But that does not yield the result I'm after.
The problem is that when I run that code I receive the following:
array [
"NN" => 1
]
But I expected this:
array [
1,
2,
3
]
Any idea how to approach this?
Thanks in advance,
pack creates a 16-character string.
$str = pack('JNN', 1, 2, 3);
//string(16) "\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03"
unpack requires keys for the format elements. Example:
$arr = unpack('Jint64/N2int32_',$str);
/*
array (
'int64' => 1,
'int32_1' => 2,
'int32_2' => 3,
)
*/
For more examples, see Unpack in the PHP manual.
If purely numeric keys are required, the array_values function can be used.

Laravel whereIn implementation of whereJsonContains

I have this code that works fine and returns 1 item collection:
$myCollection = MyModel::whereJsonContains('payload->ProductCode->id', "1")->get();
I however want to fetch the $myCollection not just when the value is 1 but when it is contained in one of many array items.
$array = [0 => 1, 1 => 2, 2 => 3];
$myCollection = MyModel::whereJsonContains('payload->ProductCode->id', $array)->get();
UPDATES
When I try this code it return an empty data. I mean when I use 1 instead of "1". Could that be the reason why it doesn't work when I use an array?
$myCollection = MyModel::whereJsonContains('payload->ProductCode->id', 1)->get();
A sample of what the payload contains is this. I suppose that could give more clarity to my question:
{
"ProductCode": {
"id": "1",
"name": "My Service",
}
}
Running the above code returns an empty data. How do I fix this please?
You need to follow your query as below.
$array = [0 => 1, 1 => 2, 2 => 3];
// Eloquent
PaymentTransaction::whereJsonContains('payload->ProductCode->id',$array)->get();;
// or
PaymentTransaction::jsonContains('payload->ProductCode->id', $array)->get();
you can try it as below too.
$array = [0 => 1, 1 => 2, 2 => 3];
$array = array_values(array_map('strval',$array));
PaymentTransaction::where(function ($query) use ($array) {
foreach ($array as $id) {
$query->orWhereJsonContains('payload->ProductCode->id', $id);
}
})->get();
I think the first part of #Dilip's answer is not correct as I had the same issue with whereJsonContains on laravel 8. It would return empty result if the field is not a JSON array. The second part of his answer solves the issue but doesn't point the problem here.
The whereJsonContains method is used to query JSON array fields which in your case, payload->ProductCode->id is not an array field. That's why you get empty array.
Now as you are looking for rows that the payload->ProductCode->id contained within your $array, the whereIn method is the method you are looking for.
As Laravel document says, "The whereIn method verifies that a given column's value is contained within the given array". So you code would be like this:
$array = [ 1, 2, 3];
$myCollection = MyModel::whereIn('payload->ProductCode->id', $array)->get();
// $myCollection contains rows that their `payload->ProductCode->id` is contained within [1, 2, 3] array.
You could use whereJsonContains method if your data was like this:
{
"ProductCode": {
"id": ["1", "2"],
"name": "My Service",
}
...
}

Laravel request is an array but not recognized by count()

I am passing an array into my controller via axios.post request. I am trying to get the length of the $request array that I am passing to the controller. However, I keep recieving a "Parameter must be an array or an object that implements Countable" error.
Here is what my array looks like:
array (
0 =>
array (
'text' => 'It is this',
'question_id' => 98,
),
1 =>
array (
'text' => 'And it is that',
'question_id' => 98,
),
2 =>
array (
'text' => 'Also a little bit of this',
'question_id' => 98,
),
Here is what I have tried:
$count = sizeof($request));
$count = $request->length;
$count = count($request);
The only thing that has had even a little bit of success is doing:
$count = count($request[0])
This returns 2, which is for the elements inside the first array. It counts text, and question_id. While this is good progress this is not what I want
What I would like to see happen is to have the length of the entire $request object. In the example I gave above, I would like to either receive 2, (the end of 0,1,2) or 3 (the count of 0,1,2).
If $request is an Illuminate\Http\Request, it won't be directly countable.
You can count $request->all() or $request->input(), though.
What about:
count($request->all());
In as much as the accepted answer will count the number of items in the requests, it will not count the number of items in a single request request item say C. If you are sure that C is an array and C is part of the request then doing count($request->C) not e that count here is a regular PHP function
try ;
count($request->all());

Laravel Stuck with returning a json request -> Integer Array -> receiving Eloquent Models

I tried to answer a JSON Request, returning Laravel-Models on the delivered id's in the request.
This is my - JSON-Request
{
"places": [1,2, 3, 4, 5]
}
First i transform it to an array:
Convert Request to Array
$array = $request->places;
Output:
array:5 [
0 => 1
1 => 2
2 => 3
3 => 4
4 => 5
]
And this is how i would receive all Models (1,2 are the manually entered id's in this example:
Get all Places
$posts = Post::whereIn('place_id',[1,2] )->get();
My Problem, the placeholder [1,2] only allows a list of Integer. But I'm not able to transform my array into the placeholder variable like this.
$posts = Post::whereIn('place_id',[$request] )->get();
If i put the Array into a String variable, lets say: $request = "1,2,3,4,5" then, I only receive Models from the first Value (number 1 in this case).
Is there any way to transform my JSON-Requests to receive all Laravel Models?
Any help will be appreciated,
Cheers Sebastian
You should try something like this.
$posts = Post::whereIn('place_id', $request->request->get('places', []))->get();
When your request body is.
{
"places": [1, 2, 3, 4, 5]
}

POSTing a multidimensional array from Python

I'm trying to POST an array to a RESTful PHP API. The idea is to allow (n>0) records, each containing a remote_id, a dimension_id and a metric.
Here's my client Python:
data = urllib.urlencode([
("remote_id", 1),
("dimension_id", 1),
("metric",metric1),
("remote_id", 1),
("dimension_id", 2),
("metric",metric2)
])
response = urllib2.urlopen(url=url, data=data)
And here's my serverside PHP
<?php
print_r($_POST);
?>
This returns, predictably:
Array
(
[remote_id] => 1
[dimension_id] => 2
[metric] => 16
)
It looks to me like I'm overwriting every instance of remote_id, dimension_id and metric with the final values, which is unsurprising since they're all keyed with identical names.
What's the proper way to do this? I can see a horrible method with unique keys (1_remote_id, 1_dimension_id, 1_metric + 2_remote_id, 2_dimension_id, 2_metric) but that doesn't scale very well.
I guess I'm after something like this PHP, but in Python:
<?php
$observations = array();
$observations[] = [
"remote_id" => "a1",
"metric_id" => "foo",
"metric" => 1
];
$observations[] = [
"remote_id" => "a1",
"metric_id" => "bar",
"metric" => 2
];
?>
Appreciate any tips!
Sam
Don't quote me on this (I haven't done any PHP in a LOOONG time), but this may just work:
data = urllib.urlencode([
("remote_id[]", 1),
("dimension_id[]", 1),
("metric[]",metric1),
("remote_id[]", 1),
("dimension_id[]", 2),
("metric[]",metric2)
])
I would give it a try anyway.

Categories