Laravel eloquent gives array of numbers, instead of integers - laravel

I'm trying to return id's as a string and pass them via api (using for select later)
Using Laravel resouces:
public function toArray($request)
{
return [
'speciality' => $this->specialities()->pluck('speciality_id')
];
}
and it returns an array of numbers, like:
[1, 3, 5, 7]
How can I convert them within eloquent query and return like a string?
["1", "3", "5", "7"]

You could loop through the array, cast it to string and add to new array as it is only required for this specific case.
$a = [1, 3, 5, 7];
$b = array();
foreach($a as $as)
$b[] = (string)$as;
return $b;
Or better use array_map() -
$a = array_map(function($value){
return (string) $value;
}, $a);

It's a bit awful, but if have no choice then
cast it to string
protected $casts=[
'speciality_id'=>'string'
];

Related

Laravel collection opposite of diff

i have 2 collections:
$collection = collect([1,2,3,4]);
$collection2 = collect([1,5,6,4]);
with:
$collection->diff($collection2);
i get [2,3]
so what i want is to have the opposite value, [1,4]
Is there a way or method in collection to make this?
You can use duplicates method after mergging into single collection
$collection1 = collect([1,2,3,4]);
$collection2 = collect([1,5,6,4]);
$duplicates = $collection1
->merge($collection2)
->duplicates()
->values();
Will give you
Illuminate\Support\Collection {#1151
all: [
1,
4,
],
}
laravel collection intersect
intersect method removes any values from the original collection that are not present in the given array or collection.
$collection = collect([1,2,3,4]);
$collection2 = collect([1,5,6,4]);
$intersect = $collection->intersect($collection2);
$intersect->all();

Laravel: Access Rules::in variable items

How to access the items listed in an Illuminate\Validation\Rules\In variable ?
use Illuminate\Validation\Rules\In;
$foo = Rule::in('a', 'b');
$foo->toString() // error
The only way I found to show it is:
>>> dump($foo)
Illuminate\Validation\Rules\In^ {#3512
#rule: "in"
#values: array:2 [
0 => "a"
1 => "b"
]
}
you can convert that Illuminate\Validation\Rules\In to collection then take the result array:
$foo = Rule::in('a', 'b');
$values = collect($foo)->values()[1];
to get the string Representation from it:
$stringRepresentation=$foo->__toString();

Count number of same values in JSON array and convert it to string

My JSON looks something like this:
[
{"pet_type":"Dog","weight":"26","description":"Akita"},
{"pet_type":"Dog","weight":"6","description":"Pug"},
{"pet_type":"Cat","weight":"4","description":"Manx"},
{"pet_type":"Dog","weight":"12","description":"Beagle"},
{"pet_type":"Cat","weight":"5","description":"Siberian"}
]
How could I convert it to a string which would look like3 Dogs, 2 Cats?
The way I tried is filling an array with pet_type and than use array_count_values to count number of same records, and later I go through that array in a foreach and concat string like this:
foreach ($count_animals as $type => $number) {
$animals .= $number.' '.str_plural($type, $number).', ';
}
This works, but my question is, could I do it with less code, directly from JSON, without using one more foreach loop?
If it works, you can keep your code.
If you want less code, you can use this version :
$json = '[
{"pet_type":"Dog","weight":"26","description":"Akita"},
{"pet_type":"Dog","weight":"6","description":"Pug"},
{"pet_type":"Cat","weight":"4","description":"Manx"},
{"pet_type":"Dog","weight":"12","description":"Beagle"},
{"pet_type":"Cat","weight":"5","description":"Siberian"}
]';
print_r(array_count_values(array_map(function($item) {
return $item['pet_type'];
}, json_decode($json, true))));
Gonna display :
Array ( [Dog] => 3 [Cat] => 2 )
in your controller
$pet = Pet::get();
$petcount = Pet::where('pet_type','Dog')->get();
In your blade
<h1>{{count($petcount)}} Dog</h1>

JSON is object instead of array, if array_diff returns assoc array on Collection->toArray()

My issue is in my json I am expecting an array, but am getting an object.
Details:
I have an array of numbers:
$numbers = [1];
I select from relationship, the "drawn numbers":
$drawnNumbers = Ball::whereIn('number', $numbers)->where('game_id', $card->game->id)->get()->map(function($ball) {
return $ball->number;
})->toArray();
I do a ->toArray() here. I want to find the numbers in $numbers that do not occur in $drawnNumbers. I do so like this:
$numbersNotYetDrawn = array_diff($numbers, $drawnNumbers);
My method then return $numbersNotYetDrawn (my headers accept is application/json).
So now the issue. When $drawnNumbers is an empty array, then the printed json is a regular array like this:
[
1
]
However if the relationship returns $drawnNumbers to be an array with numbers, then json is printed as an object:
{
"0" => 1
}
Does anyone know why this is? Anyway to ensure that json is array?
Edit:
Here is my actual data:
$drawnNumbers = Ball::whereIn('number', $numbers)->where('game_id', $card->game->id)->get()->map(function($ball) {
return $ball->number;
})->toArray();
$undrawnNumbers = array_diff($numbers, $drawnNumbers);
// $undrawnNumbers = array_values(array_diff($numbers, $drawnNumbers)); // temp fix
Replace
$numbersNotYetDrawn = array_diff($numbers, $drawnNumbers);
with
$numbersNotYetDrawn = array_values(array_diff($numbers, $drawnNumbers));
to make sure element keys are reset and array is treated as a simple list and serialized to a JSON list - instead of being treated as an associative array and serialized to a JSON object.
I recently had this same problem and wondered the same thing.
I solved it by adding "array_values", but I was wondering how to reproduce it.
I found it that it is reproduced when array_diff removes an element from the array that isn't the last element. So:
>>> $x
=> [
1,
2,
3,
4,
5,
]
>>> array_diff($x, [5]);
=> [
1,
2,
3,
4,
]
>>> array_diff($x, [1]);
=> [
1 => 2,
2 => 3,
3 => 4,
4 => 5,
]

Check if a value is present in a comma separated varchar string

I have a record "id_zone" in database that store cites id like this $abilitato->id_zone = '1, 2, 3, 9, 50'
From laravel i need to check if a value passed from url is present in this field. The following work only if i have a single value
$abilitato = \App\Models\Servizi::where('id', $servizio)->('id_zone', $verifica->id_citta)->first();
if(!empty($abilitato) && empty($verifica->multicap)) {
$json = ['CAP' => '1' , 'DEB' => $cap ];
}else{
$json = ['CAP' => '0' , 'DEB' => $cap];
}
i need to check if
If you want to know if a value is in your array you can use this functiĆ³n to know it.
here is a example:
// First convert your string to array
$myString = $abilitato->id_zone; // Here your string separate with comas
$array = explode(',', $myString); // Here convert it to array
$value = 7; // Here you put the value that you want to check if is in array
// Check if exist a value in array
if (in_array($value, $array)){
echo "Exist in array";
}else{
echo "No exist in array";
}
This is the documentation of these functions: explode , in_array
Regards!

Resources