Laravel: custom array validation depends on previous selected value - laravel

Laravel version: 7.x
I have tested the code with hard-coded valid device_company_id (which is associated with the selected device) and it works fine.
Tables
device_companies
|- id
|- company_id
|- title
|- ...
devices
|- id
|- device_company_id
|- ...
Request data
Array
(
...
[devices] => Array
(
[0] => Array
(
[device_company_id] => 1
[device_id] => 2
[device_inventory_id] => null
[amount] =>
[refundable] =>
[description] =>
)
)
)
Rules:
...
$rules = array_merge($rules, [
'devices' => [
'required',
'array'
],
'devices.*.device_company_id' => [
'required',
'integer',
'exists:device_companies,id,company_id,' . auth()->user()->id
],
'devices.*.device_id' => [
'required',
'integer',
'exists:devices,id,device_company_id,devices.*.device_company_id'
],
]);
...
I need a custom validation rule for the exists validator to validate if device actually belongs the selected device_company or not. Because I don't want anyone opening the inspect tool, change the value and causing the application an error or anything like that.

Here is the link where I found the reference https://ericlbarnes.com/2015/04/04/laravel-array-validation/
My code:
...
$rules = [
...other rules
];
$newRules = [
'devices' => [
'required',
'array'
],
'devices.*.device_company_id' => [
'required',
'integer',
'exists:device_companies,id,company_id,' . auth()->user()->id
],
];
foreach($data['devices'] as $key => $array)
{
$newRules["devices.{$key}.device_id"] = [
'required',
'integer',
"exists:devices,id,device_company_id,{$array["device_company_id"]}",
];
}
$rules = array_merge($rules, $newRules);
...
Although, this code is working for me but I feel its not the proper way to do it. It feels kind of a way around instead of the proper solution. If anyone finds a better solution then please do post your answer.
Hope this can be helpful for someone. Thanks :)

Related

yii2 pagecahe array dependecny

I am implementing page cache for one of my page. For depenedency, I have to check an array, which can be either exist or not. Possible array keys cane ,
usersearch['id'], usersearch['name'], usersearch['phone]. I have to add dependency for any change in these values as well.
Also, I have to clear cache for any update or add in user table.
Is there any possible solution for this.?
Thanks in advance
You can use variations
public function behaviors(){
$usersearch = Yii::$app->requst->get('usersearch');
return [
[
'class' => 'yii\filters\PageCache',
'only' => ['index'],
'duration' => 60,
'variations' => [
'YOUR_DYNAMIC_VALUE1','YOUR_DYNAMIC_VALUE2'
],
'dependency' => [
'class' => 'yii\caching\DbDependency',
'sql' => 'SELECT COUNT(*) FROM post',
],
],
];
}
Ref link
IN YOUR CASE ,you can use
'variations' => \Yii::$app->requst->get('usersearch')??[],
or
'variations' => [
\/Yii::$app->requst->get('usersearch')['id'] ?? '',
\Yii::$app->requst->get('usersearch')['name'] ?? '',
\Yii::$app->requst->get('usersearch')['phone'] ?? '',
]
You could use a yii\caching\FileCache component with the following configuration.
Firstly, you set the cache in the init function of your controller:
Yii::$app->setComponents([
'yourCacheName' => [
'class' => \yii\caching\FileCache::class,
'defaultDuration' => 1800, //cache duration in seconds
'keyPrefix' => Yii::$app->getSession()->getId(). '_'
]
]);
Here, the parameter keyPrefix is set so that it is linked to the session ID. Thus, the visitors do not see each other's cached page. If the content is static and equal, regardless of the user or the session, this parameter can be removed.
In the view that must be cached you can call the beginCache function and the dependency as follows:
$this->beginCache('cache-id', [
'cache' => Yii::$app->yourCacheName, // the name of the component as set before
'variations' => [
$usersearch['id'] ?? '',
$usersearch['name'] ?? '',
$usersearch['phone'] ?? '',
],
'dependency' => [
'class' => \yii\caching\DbDependency::class,
'sql' => 'SELECT count(*) FROM your_user_table'
]
]);
// your view
$this->endCache();

Laravel: How can I assertJson an array

I am creating a feature test for a Seminar. Everything is working great; I am trying to update my feature test to account for the seminar dates.
Each Seminar can have one or many dates, so I am saving these values as a json field:
// migration:
...
$table->json('dates');
...
Here is what my Seminar model looks like:
// Seminar.php
protected $casts = [
'dates' => 'array',
];
When saving the seminar, I am returning a json resource:
if ($seminar->save()) {
return response()->json(new SeminarResource($seminar), 200);
...
Using Postman, my Seminar looks a like this:
...
"capacity": 100,
"dates": [
"2020-10-15",
"2020-10-16"
],
...
So far so good!
In my test, I am testing that a seminar can be created.
$http->assertStatus(201)
->assertJson([
'type' => 'seminars',
'id' => (string)$response->id,
'attributes' => [
'dates' => $response->attributes->dates, // General error: 25 column index out of range
I've tried to convert the array to a string, or json_encode the value in the resource. I don't think that's the correct way since I am already casting the value as an array in the model.
How can I assert that my dates is returning an array?
+"dates": array:2 [
0 => "2020-10-15"
1 => "2020-10-16"
]
Thank you for your suggestions!
EDIT
When I dd($response->attributes->dates); this is what I'm getting (which is correct).
array:2 [
0 => "2020-10-15"
1 => "2020-10-16"
]
What I'm not sure is how to assert an array like that. Since I'm using faker to generate the date, I don't really know (or care) what the date is, just want to assert that it is in fact an array.
I've tried something like:
'dates' => ['*'],
However, that just adds another element to the array.
EDIT 2
If I make the array a string,
'dates' => json_encode($response->attributes->dates),
I'll get an error like this:
--- Expected
+++ Actual
## ##
- 'dates' => '["2020-10-15","2020-10-16"]',
+ 'dates' =>
+ array (
+ 0 => '2020-10-15',
+ 1 => '2020-10-16',
+ ),
In my database, the values are stored like this:
["2020-10-15","2020-10-16"]
My actual test looks like this:
$http->assertStatus(201)
->assertJsonStructure([
'type', 'id', 'attributes' => [
'name', 'venue', 'dates', 'description', 'created_at', 'updated_at',
],
])
->assertJson([
'type' => 'workshops',
'id' => (string)$response->id,
'attributes' => [
'name' => $response->attributes->name,
'venue' => $response->attributes->venue,
'dates' => $response->attributes->dates,
'description' => $response->attributes->description,
'created_at' => (string)$response->attributes->created_at,
'updated_at' => (string)$response->attributes->updated_at,
],
]);
$this->assertDatabaseHas('workshops', [
'id' => $response->id,
'name' => $response->attributes->name,
'venue' => $response->attributes->venue,
'dates' => $response->attributes->dates,
'description' => $response->attributes->description,
]);

Laravel unique validation Ignore Rule for update

I have a name field on my Client model which must be unique. For the store method I have the following rules:
array (
'token' => 'string|max:250',
'directory' => 'max:250',
'name' => 'required|string|max:250|unique:clients',
)
For the update method, I have amended this ruleset to ignore the current ID to avoid a duplicate being identified:
$rules['name'] = $rules['name'] . ',id,' . $id;
This produces the following ruleset (for record ID 105):
array (
'token' => 'string|max:250',
'directory' => 'max:250',
'name' => 'required|string|max:250|unique:clients,id,105',
)
When the update method is executed, the The name has already been taken. response is returned during the validation.
I realise this is a well-discussed topic, but believe I am conforming to the correct approach. Can someone point out the error in my logic, please?
Note: This is running on Laravel 5.8.
array(
'token' => 'string|max:250',
'directory' => 'max:250',
'name' => [
'required', 'string', 'max:250',
\Illuminate\Validation\Rule::unique(Client::class, 'email')->ignore($this->id)
]
)

Guzzle Post Null/Empty Values in Laravel

I've been trying to work with Guzzle and learn my way around it, but I'm a bit confused about using a request in conjunction with empty or null values.
For example:
$response = $client->request('POST',
'https://www.testsite.com/coep/public/api/donations', [
'form_params' => [
'client' => [
'web_id' => NULL,
'name' => 'Test Name',
'address1' => '123 E 45th Avenue',
'address2' => 'Ste. 1',
'city' => 'Nowhere',
'state' => 'CO',
'zip' => '80002'
],
'contact' => [],
'donation' => [
'status_id' => 1,
'amount' => $donation->amount,
'balance' => $donation->balance,
'date' => $donation->date,
'group_id' => $group->id,
],
]
]);
After running a test, I found out that 'web_id' completely disappears from my request if set to NULL. My question is how do I ensure that it is kept around on the request to work with my conditionals?
At this point, if I dd the $request->client, all I get back is everything but the web_id. Thanks!
I ran into this issue yesterday and your question is very well ranked on Google. Shame that it has no answer.
The problem here is that form_params uses http_build_query() under the hood and as stated in this user contributed note, null params are not present in the function's output.
I suggest that you pass this information via a JSON body (by using json as key instead of form_params) or via multipart (by using multipart instead of form_params).
Note: those 2 keys are available as constants, respectively GuzzleHttp\RequestOptions::JSON and GuzzleHttp\RequestOptions::MULTIPART
Try to define anything like form_params, headers or base_uri before creating a client, so:
// set options, data, params BEFORE...
$settings = [
'base_uri' => 'api.test',
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'ajustneedatokenheredontworry'
],
'form_params' => [
'cash' => $request->cash,
'reason' => 'I have a good soul'
]
];
// ...THEN create your client,
$client = new GuzzleClient($settings);
// ...and finally check your response.
$response = $client->request('POST', 'donations');
If you check $request->all() at the controller function that you are calling, you should see that were sent successfully.
For those using laravel, use this:
Http::asJson()

Installing user-management for Yii2.0

I've been trying to install user-management for Yii2.0, but getting ReflectionException while loading the page. I have attached the error page and directory structure below.
and the file path is as shown below.
I've searched a lot to find out the reason for this, but nothing worked out. can someone tell me what am I missing here to get it work. looks like the user-management installation documentation has some flaws. It is not clear enough to understand. Hope to get the steps to install. Thanks
Here is my console/web.php
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'gAry7SfUr0oOjNQDqItsobmGBcJajQoW',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
//'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
'class' => 'app\webvimark\modules\user-management\components\UserConfig',
// Comment this if you don't want to record user logins
'on afterLogin' => function($event) {
\webvimark\modules\user-management\models\UserVisitLog::newVisitor($event->identity->id);
}
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
],
'modules'=>[
'user-management' => [
'class' => 'webvimark\modules\user-management\UserManagementModule',
// 'enableRegistration' => true,
// Here you can set your handler to change layout for any controller or action
// Tip: you can use this event in any module
'on beforeAction'=>function(yii\base\ActionEvent $event) {
if ( $event->action->uniqueId == 'user-management/auth/login' )
{
$event->action->controller->layout = 'loginLayout.php';
};
},
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
return $config;
It seems to have a slight difference with the expected configuration for this extension.
Use this
'class' => 'webvimark\modules\UserManagement\components\UserConfig',
ie UserManagement instead of user-management is a configuration path and not a route

Resources