Laravel - Access Config value using a wildcard? - laravel

Let's say that I have a config file called templates.php
It stores a list of types and items.
Now, I know that in order to obtain a specific row I could just do Config::get("list.type1.item1");
<?php
return [
'list' => [
'type1' => [
'item1' => [
//
],
'item2' => [
//
],
'item3' => [
//
],
],
]
];
But the thing is that 'type1' is dynamic, so I need a way to get all elements that matches item name.
Something like this (wildcards are not supported, so it doesn't work)
Config::get("list.*.item1");
What's the fastest (okay, that doesn't actually matter, I just want to know if it can be done at all) possible way to achieve this?

You only need to put your dynamic type on a variable let's says:
$type = 'type1';
config('services.' . $type . '.item1');

Related

How with laravel/pint to make keys and values are aligned with spaces on the same level?

In Laravel 9 app using laravel/pint (1.4) with "psr12" preset I prefer to see not code :
\DB::table('quizzes')->insert([
'id' => 2,
'question' => 'What does ORM stand for?',
'quiz_category_id' => 1,
'points' => 4,
'active' => true,
]);
But:
\DB::table('quizzes')->insert([
'id' => 2,
'question' => 'What does ORM stand for?',
'quiz_category_id' => 1,
'points' => 4,
'active' => true,
]);
where keys and values are aligned with spaces on the same level.
I tried to fix it and found property “binary_operator_spaces”
But looking at docs :
https://github.com/laravel/pint/blob/main/resources/presets/laravel.php
I see only 1 rule :
'binary_operator_spaces' => [
'default' => 'single_space',
],
Not sure, but how can I set this rule? Seems it does not hae any other rules...
Thanks!
Check the documentation for binary_operator_spaces
You want to use that rule with the align_single_space_minimal option:
'binary_operator_spaces' => [
'default' => 'align_single_space_minimal',
],
That is if you have the same setup as shown in the link you provided
If you were using PHPCodeSniffer (which is what laravel is using behind the scenes) you would simply use it this way:
$config->setRuleset([
'Squiz.WhiteSpace.OperatorSpacing' => [
'align_single_space_minimal' => true
]
]);
Just remember that each space is 1 byte, and those add up... a pedantic-thought but one to keep in your head none-the-less (imho no one should use this rule or add pointless whitespace to array)

Row inserted but number not

I trying to insert a row in codeigniter and row inserted.
Problem is all row inserted properly but in sql bighint(11) field inserted 0.
I checked properly in array value given.
$data = [
'sku' => $POST['rec1'],
'pruch_price' => $POST['rec2'],
'sell_price' => $POST['rec3']
];
$model->insert ($data);
you should use $_POST[] instead of $POST.
But better yet, don't send $_POST directly to the models, instead use the post request provided by Codeigniter 4.
$data = [
'sku' => $this->request->getPost('rec1'),
'pruch_price' => $this->request->getPost('rec2'),
'sell_price' => $this->request->getPost('rec3')
];
$model->insert($data);

How to check for null in other field laravel FormRequest?

I am trying to exclude a field from being validated when another field has a value (not null). In this case, i want 'deleted_pictures' to be excluded if product_pictures is an array (not null). My problem is that i think exclude_unless:product_pictures,null evaluates null as a string, and not as, well, null.
This is my rule.
ProductRequest.php
return [
'product_pictures.*' => 'required_with:product_pictures|file|max:2048|mimes:jpeg,jpg,png',
'product_pictures' => 'sometimes|array',
'deleted_pictures' => ['exclude_unless:product_pictures,null', 'required', new cant_delete_all($max,'1')],
];
read : exclude deleted_pictures unless product_pictures has a value of 'null'
I tried this to confirm my suspicion and it works like it should.
//test_field = 'some_value'
return [
'test_field' => 'required|string'
'product_pictures.*' => 'required_with:product_pictures|file|max:2048|mimes:jpeg,jpg,png',
'product_pictures' => 'sometimes|array',
'deleted_pictures' => ['exclude_unless:test_field,some_value', 'required', new cant_delete_all($max,'1')],
];
read : exclude deleted_pictures unless test_field has a value of 'some_value'
In my first case, deleted_pictures is excluded because it doesn't detect that product_pictures is 'null' (string)
While on the second case, deleted_pictures is NOT excluded because test_field matches the given value.
My question is, how do you evaluate null value in FormRequest Laravel?
So apparently you can just leave the second parameter blank to evaluate it as null
return [
'product_pictures.*' => 'required_with:product_pictures|file|max:2048|mimes:jpeg,jpg,png',
'product_pictures' => 'sometimes|array',
'deleted_pictures' => ['exclude_unless:product_pictures,', 'required', new cant_delete_all($max,'1')],
];
I'm not sure if this is how its supposed to be done or intended behavior. But im just gonna leave this answer just in case someone might need it. If someone can suggest the 'proper' way of doing it then I'll accept that instead.

How to get an array of 2-tuples from Laravel query builder?

Basically, I want to do this:
$locals['companies'] = Company::orderBy('name')->get(['id','name'])->map(function($c) { return [$c->id, $c->name]; })->toArray();
But without such a verbose map function. Isn't there a get-like method that will return flat numeric arrays instead of objects?
To be clear, the output should look like this:
array:4 [
0 => array:2 [
0 => 4
1 => "My Company"
]
1 => array:2 [
0 => 14
1 => "Example Company"
]
2 => array:2 [
0 => 13
1 => "Best Company"
]
3 => array:2 [
0 => 12
1 => "Super Co"
]
]
This is what I mean by 2-tuples: two-element numeric arrays. I know they don't exist in PHP, but the concept is the same; each entry has a fixed length.
There is no function out of the box to do this, but Laravel's Collection is Macroable, so you can add your own function to it to do this.
For example, somewhere in your code (like the boot() method of your AppServiceProvider), you can add a new method to the Collection:
// add toIndexedArray method to collections
\Illuminate\Support\Collection::macro('toIndexedArray', function() {
return array_map('array_values', $this->toArray());
});
Now you can use this new method like any other normal Collection method, so your final code would be:
$locals['companies'] = Company::orderBy('name')->get(['id','name'])->toIndexedArray();
If this is something you need a lot, you can change the PDO fetch mode in config/database.php to PDO::FETCH_NUM. I'm assuming it's possible to change it on-the-fly as well, but the code probably won't look that great. I don't think there's a Laravel command to change it for a single query, I'm afraid.
Otherwise, since the array is multidimensional, I'm afraid you do need to map over them somehow, and Laravel collections don't work nicely with e.g. ->map('array_values') which would have been a lot cleaner.
You could wrap it in array_map('array_values', $array) but that seems silly.
At least you could make it a little shorter if you change ->map() to ->transform() - then you don't need to tack on the ->toArray() at the end.
Use pluck():
$locals['companies'] = Company::orderBy('name')->pluck('id', 'name')->toArray();
If you need a list for Form::select this will work:
$locals['companies'] = Company::orderBy('name')->pluck('name', 'id');
You can omit the map function and just do:
$locals['companies'] = Company::orderBy('name')->get(['id','name'])->toArray();

With a hash of lists how do I operate on each key/list element once in random order?

For example, if my HoL looks like:
%HoL = (
"flintstones" => [ "fred", "barney" ],
"jetsons" => [ "george", "jane", "elroy" ],
"simpsons" => [ "homer", "marge", "bart" ],
);
And I want to create a loop that will allow me to operate only once on each key/element pair in a completely random order (so that it jumps between keys randomly too, not just elements), how do I do that? I'm thinking it will use shuffle, but figuring out the specifics is defeating me.
(Sorry for noobishness of question; I haven't been coding long. I was also unable to find an answer for this specific problem by googling, though I daresay it's been answered somewhere before.)
Build an array of all key-value pairs, then shuffle that:
use List::Util 'shuffle';
my %HoL = (
"flintstones" => [ "fred", "barney" ],
"jetsons" => [ "george", "jane", "elroy" ],
"simpsons" => [ "homer", "marge", "bart" ],
);
# Build an array of arrayrefs ($ref->[0] is the key and $ref->[1] is the value)
my #ArrayOfPairs = map {
my $key = $_;
map { [ $key, $_ ] } #{$HoL{$key}}
} keys %HoL;
for my $pair (shuffle #ArrayOfPairs) {
print "$pair->[1] $pair->[0]\n";
}

Resources