How to access Laravel validation translations - laravel

As we know, to use validators and translate messages we need to use field.validatorname with translated text.
So now I have entry.php file with my translation:
return [
'validation' => [
'title.max' => 'some text',
]
];
validator will use this text without a problem. The question is - how to access this text using trans / Lang::get() ?
For example using trans('entry.validation.title.max') won't work. I tried using [] for example trans('entry.validation[title.max]') but it also doesn't work.
The only way it works is using array dereference syntax:
trans('entry.validation')['title.max']
Is there any other way?

Related

How to pass an array to Laravel Route parameter

I wanted to pass a value of typed array to my route parameter, the array could be in any size and a different key-value pairs each time.
Route::get('/example/{array}', ...
So if I have an array like this:
$array = [
'a' => 'one',
'b' => 1,
...
]
I did this but knew already it ain't gonna work because it looks like I'm passing values to my route parameters named a, b, etc.
route('route.name', $array)
As expected the error says:
... [Missing parameter: array]
So I used the serialize().
route('route.name', serialize($array))
I'm still getting an error, something like:
[Missing parameter: s:1:"a";i:1;s:1:"b";i:2;]
What am I missing ? I also don't understand what the last error says.
PHP have for this the http_build_query function.
$array = [
'a' => 'one',
'b' => 1,
];
$query = http_build_query(array('myArray' => $array));
// output: myArray%5Ba%5D=one&myArray%5Bb%5D=1
When passing data to a route in Laravel you should make a practice of passing that data in an array like so:
Route:
Route::get('/example/{array}', ...
Calling the named route:
route('route.name', ['array' => serialize($array)])
I don't know if this formatting is required, but it 1. helps you to better format your routes when passing multiple values, and 2, makes your code more readable.
Laravel Routing Documentation
I found the same problem, and from the tests I did, it seems to be an incompatibility between php and Laravel.
What happens is that php serialize() (and also php json_encode()) use the character «{». This character seems to confuse Laravel router, so the error message.
I have tried to use php htmlspecialchars(serialize($array)) (and other combinations like htmlentities(json_encode($array))) but the problem is that «{» is a normal character so they do not transform it (so continues confusing the Laravel router).
I also tried the solution of Maik Lowrey, but then I do not see an out of the box method to recover the array from the serialized parameter on the other side of the route (urldecode() does nothing).
At last I have used the following ugly turnaround that only works for one-dimension arrays (but works):
In the blade route generation:
['arrayParameter' => trim(json_encode($array), '{}')]
In the Controller function:
$array = json_decode('{' . $arrayParameter . '}', true);
Best regards.

Laravel Validator "in:" not seeing first element

I have the following ruleset. The "in:" rules will fail with not found if the first element in the array is entered in the input field. However if 2nd or subsequent elements are selected then the rule fires ok. Has anyone else had this issue? I am using "Laravel 7"
"title": "required|min:2|max:50|regex:/^[a-zA-Z][a-zA-Z ]+$/u",
"target_start_date": "required|date_format:Y-m-d|after_or_equal:today",
"target_finish_date": "required|date_format:Y-m-d|after_or_equal:target_start_date",
"genre": "required|in:[adventure,action,biographical,contemporary,crime,thriller,mystery,fantasy,historical,horror,medical,myths,political,romance,sci_fi,war]",
"visibility": "required|in:[public,friends,public]",
"owner_starts": "required|in:[yes,no,sequence,random]",
"owner_finishes": "required|in:[yes,no,sequence,random]"
That’s not how you specify values for the in rule; you just specify the options as comma-delimited strings. For example:
'visibility' => ['required', 'in:public,friends'],
(I’ve also used the “array” syntax for specifying rules, as it makes each individual validation rule easier to see rather than a long string full of | characters.)
If the available options are stored as an array elsewhere in your application, such as a repository or a configuration file, then you can pass that array of options directly to the “fluent” rule builder as per Charlie’s answer:
'genre' => [
'required',
Rule::in($genres),
],
Be sure to import Illuminate\Validation\Rule if you want to use this approach.
"owner_finishes": "required|in:[yes,no,sequence,random]"
Should be:
use Illuminate\Validation\Rule;
'owner_finishes' => [
'required',
Rule::in(['yes', 'no', 'sequence', 'random']),
],
As the docs says:
Since this rule often requires you to implode an array, the Rule::in method may be used to fluently construct the rule:

Laravel Localization position depend on variable

I want to make standard request for laravel localization file: animals.php
which looks like:
<?php
return [
'dog' => 'dog trans',
'cat' => 'cat trans',
'super-mutant-spider' => 'super-mutant-spider trans',
];
Now when I'm accessing this, I'm simply writing:
trans('animals.dog') -> gives dog trans etc.
this is fine,
now I want to make it depend on the user variable animal:
so when $user->animal is 'dog' I want dog trans result.
so when I try: trans('animals.$user->animal') it will not work
How can I code it?
This is basic string concatenating.
What you need is basically this: trans('animals.' . $user->animal)
You have detailed explanation on PHP - concatenate or directly insert variables in string

Reverse construction of Custom Routes from inside a Controller using Pimcore 5.x

As per the Pimcore 5 Documentation:
URLs are generated using the default URL helper of Symfony $this->path() and $this->url(). Additionally to the standard helpers for generating URLs, Pimcore offers a special templating helper ($this->pimcoreUrl()) to generate URLs like you did with Pimcore 4. You can define a placeholder in the reverse pattern with %NAME and it is also possible to define an optional part, to do so just embrace the part with curly brackets { } (see example below).
https://pimcore.com/docs/5.0.x/Development_Documentation/MVC/Routing_and_URLs/Custom_Routes.html
I should be able to reverse construct a route using the path method like so:
$this->path( 'MyRouteName', [
'route_param_a' => 'A',
'route_param_b' => 'B',
'route_param_c' => 'C'
] );
Unfortunately, when I call this from inside a Controller, I get the following error:
Attempted to call an undefined method named "path" of class "AppBundle\Controller\MyController".
Is there a similar function or method available in the Controller scope that I can use to generate my paths when I respond with my JSON object directly from the controller (without using a view)?
Looks like the answer for this is not covered in the Pimcore 5 documentation, rather the Symfony 3 documentation!
https://symfony.com/doc/current/routing.html#generating-urls
$url = $this->generateUrl( 'MyRouteName', [
'route_param_a' => 'A',
'route_param_b' => 'B',
'route_param_c' => 'C'
] );

required_without not working with other rules

'person.mail' =>'required_without:person.phone|sometimes|email|unique:persons,mail',
'person.phone' => 'required_without:person.mail|sometimes|regex:/[0-9]/|size:10|unique:persons,phone'
i need to validate phone and mail, one of them is mandatory
when the mail is empty and the phone isn't, the validation fails at the email rule and this goes both ways, when the mail is present and phone empty, it fails at the regex rule
how can i stop validation if value is null?
As the laravel docs state:
In some situations, you may wish to run validation checks against a
field only if that field is present in the input array. To quickly
accomplish this, add the sometimes rule to your rule list.
I get the feeling that you actually do post both person[email] and person[phone], in which case sometimes will instruct validation to continue, since the values will then be empty strings (or maybe null) rather than not present. You can conditionally add rules on other assertions than check whether key x exists by creating your own validator, and use its sometimes() method to create your own assertions:
$v = Validator::make($data, [
'person.email' => 'email|unique:persons,mail',
'person.phone' => 'regex:/[0-9]/|size:10|unique:persons,phone',
]);
$v->sometimes('person.email', 'required', function($input) {
return ! $input->get('person.phone');
});
$v->sometimes('person.phone', 'required', function($input) {
return ! $input->get('person.email');
});
The difference here is that the fields are not by default required. So for example, person.phone may either be empty, or must match your regex. If $input->get('person.email') returns a falsy value, person.phone is required after all.
As a note, I think your regex is wrong. It will pass as soon as any character inside person.phone is a number. I think you're looking for something like this:
'person.phone' => 'regex:/^[0-9]{10}$/|unique:persons,phone'
i worked it around like this, it's not the best way, but it works just fine
after the validation i added
if(empty($request->all()['person']['mail']) && empty($request->all()['person']['phone'])){
$validator->errors()->add('person.mail', 'Mail or phone required');
$validator->errors()->add('person.phone', 'Mail or phone required');
return redirect("admin/people-create")->withInput()->withErrors($validator);
}

Resources