How I can insert array data in laravel? - laravel

I want to insert data by seeder:
public function run()
{
$projects = [
[
"name" => "project-one",
"images" => ["image11.jpg", "image12.jpg", "image13.jpg"],
],
[
"name" => "project-two",
"images" => ["image21.jpg", "image22.jpg", "image23.jpg"],
],
];
Project::insert($projects);
}
images column is JSON, I get an array error on images insertion. How I can insert them?

insert() method can not use any casts of the model, it will be inserted as raw. So you just need to convert the array to a json using json_encode() function.
public function run()
{
$projects = [
[
"name" => "project-one",
"images" => json_encode(["image11.jpg", "image12.jpg", "image13.jpg"]),
],
[
"name" => "project-two",
"images" => json_encode(["image21.jpg", "image22.jpg", "image23.jpg"]),
],
];
Project::insert($projects);
}

Related

How to test array contains only objects with PHPUnit?

I'm looking for solution to test an array of objects with PHPUnit in my Laravel project.
This is my haystack array:
[
[
"id" => 10,
"name" => "Ten"
],
[
"id" => 5,
"name" => "Five"
]
]
And this is the needles array:
[
[
"id" => 5,
"name" => "Five"
],
[
"id" => 10,
"name" => "Ten"
]
]
The order of objects doesn't matter, also keys of objects doesn't matter. The only matter is we have two objects and all objects has exactly same keys and exactly same values.
What is the correct solution for this?
You can do this using the assertContainsEquals method like this:
$haystack = [
[
'id' => 10,
'name' => 'Ten'
],
[
'id' => 5,
'name' => 'Five'
]
];
$needles = [
[
'name' => 'Five',
'id' => 5
],
[
'id' => 10,
'name' => 'Ten'
]
];
foreach ($needles as $needle) {
$this->assertContainsEquals($needle, $haystack);
}
You could also a create your own assert method if you intend to perform the assertion more often:
public function assertContainsEqualsAll(array $needles, array $haystack): void
{
foreach ($needles as $needle) {
$this->assertContainsEquals($needle, $haystack);
}
}
Based on #Roj Vroemen's answer I implemented this solution for exact match asserting:
public function assertArrayContainsEqualsOnly(array $needles, array $haystack, string $context = ''): void
{
foreach ($needles as $index => $needle) {
$this->assertContainsEquals(
$needle,
$haystack,
($context ? $context . ': ' : '') . 'Object not found in array.'
);
unset($haystack[$index]);
}
$this->assertEmpty(
$haystack,
($context ? $context . ': ' : '') . 'Not exact match objects in array.'
);
}

Laravel Elasticsearch JSON Mapping Issue

I'm currently using Laravel v7.2, have the babenkoivan/scout-elasticsearch-driver installed (4.2) and am using AWS Elasticsearch 7.1. I have several tables mapped in my application that are working fine but am having issues with a nested mapping that was previously working and is now broken.
I'm saving data into a table and having that table data copied into AWS Elasticsearch. I'm using MySQL 5.6 so I am using a TEXT column to store JSON data. Data in the table looks as follows:
'id' => 1,
'results' => [{"finish":1,"other_id":1,"other_data":1}]
I have my model setup with the following mapping:
protected $mapping = [
'properties' => [
'results' => [
'type' => 'nested',
'properties' => [
'finish' => [
'type' => 'integer'
],
'other_id' => [
'type' => 'integer'
],
'other_data' => [
'type' => 'integer'
]
]
],
]
];
And if it's of any use, the toSearchableArray:
public function toSearchableArray()
{
$array = [
'id' => $this->id,
'results' => $this->results
];
return $array;
}
I have no problem creating this index and it worked up until about a couple of months ago. I don't know exactly when, as it wasn't a high priority item and may have occurred around an AWS ES update but not sure why this in particular would break. I receive the following error now:
{"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"object mapping for [results] tried to parse field [results] as object, but found a concrete value"}],"type":"mapper_parsing_exception","reason":"object mapping for [results] tried to parse field [results] as object, but found a concrete value"},"status":400}
I've tried also storing the data in the table as such, thinking it was breaking due to the potential array, but it was to no avail:
'id' => 1,
'results' => {"finish":1,"other_id":1,"other_data":1}
I'm at a loss for what else to try to get this working again.
EDIT: Here is the entire model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use ScoutElastic\Searchable;
class ResultsModel extends Model
{
use Searchable;
protected $indexConfigurator = \App\MyIndexConfiguratorResults::class;
protected $searchRules = [
//
];
protected $mapping = [
'properties' => [
'results' => [
'type' => 'nested',
'properties' => [
'finish' => [
'type' => 'integer'
],
'other_id' => [
'type' => 'integer'
],
'other_data' => [
'type' => 'integer'
]
]
],
]
];
public function searchableAs()
{
return 'results_index';
}
public function toSearchableArray()
{
$array = [
'id' => $this->id,
'results' => $this->results
];
return $array;
}
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'results_table';
}
Here is the \App\MyIndexConfiguratorResults::class
<?php
namespace App;
use ScoutElastic\IndexConfigurator;
use ScoutElastic\Migratable;
class MyIndexConfiguratorResults extends IndexConfigurator
{
use Migratable;
protected $name = "results_index";
/**
* #var array
*/
protected $settings = [
//
];
}
This is all that is needed to have Laravel automatically update AWS ES each time the table is updated. For the initial load, I would SSH in and run the following command to have it create the index. This, as well as elastic:migrate and any update/insert into the table produces the mapping error.
php artisan elastic:create-index results_index
Finally figured this out so will share the solution for anyone that runs into this. Turns out to be a fairly simple fix, though I'm not sure how it even worked in the first place so that part is still baffling.
I created a brand new index and update the mappings accordingly to add "id" and remove the type "nested" from the "results" piece. (Adding the "nested" type was adding two "results" to the index - one that contained all my nested data, the other just being "object".)
protected $mapping = [
'properties' => [
'id' => [
'type' => 'integer'
],
'results' => [
'properties' => [
'finish' => [
'type' => 'integer'
],
'other_id' => [
'type' => 'integer'
],
'other_data' => [
'type' => 'integer'
]
]
],
]
];
Then I simply added json_decode to the toSearchableArray() function as so:
public function toSearchableArray()
{
$array = [
'id' => $this->id,
'results' => json_decode($this->results, true)
];
return $array;
}
Voila. It successfully created the index and imported the data in a manner with which I can query the nested object.
Reading through the docs, the type field seems to have been removed. Scroll down to 7.x to see. Also, it seems you need to delete the index and re-add it in order for the new map to work according to this page.

Laravel array key validation

I have custom request data:
{
"data": {
"checkThisKeyForExists": [
{
"value": "Array key Validation"
}
]
}
}
And this validation rules:
$rules = [
'data' => ['required','array'],
'data.*' => ['exists:table,id']
];
How I can validate array key using Laravel?
maybe it will helpful for you
$rules = ([
'name' => 'required|string', //your field
'children.*.name' => 'required|string', //your 1st nested field
'children.*.children.*.name => 'required|string' //your 2nd nested field
]);
The right way
This isn't possible in Laravel out of the box, but you can add a new validation rule to validate array keys:
php artisan make:rule KeysIn
The rule should look roughly like the following:
class KeysIn implements Rule
{
public function __construct(protected array $values)
{
}
public function message(): string
{
return ':attribute contains invalid fields';
}
public function passes($attribute, $value): bool
{
// Swap keys with their values in our field list, so we
// get ['foo' => 0, 'bar' => 1] instead of ['foo', 'bar']
$allowedKeys = array_flip($this->values);
// Compare the value's array *keys* with the flipped fields
$unknownKeys = array_diff_key($value, $allowedKeys);
// The validation only passes if there are no unknown keys
return count($unknownKeys) === 0;
}
}
You can use this rule like so:
$rules = [
'data' => ['required','array', new KeysIn(['foo', 'bar'])],
'data.*' => ['exists:table,id']
];
The quick way
If you only need to do this once, you can do it the quick-and-dirty way, too:
$rules = [
'data' => [
'required',
'array',
fn(attribute, $value, $fail) => count(array_diff_key($value, $array_flip([
'foo',
'bar'
]))) > 0 ? $fail("{$attribute} contains invalid fields") : null
],
'data.*' => ['exists:table,id']
];
I think this is what you are looking:
$rules = [
'data.checkThisKeyForExists.value' => ['exists:table,id']
];

Override eloquent relationship result data

I use Laravel-Metable package in my project. This package return collection object using in key meta name and on value eloquent object.
Here you can see package data result screenshot.
How I can override result data and get this type of array data:
$meta = [
[
'id' => 1,
'key' => "Meta Name",
'value' => "Meta Value"
],
[
'id' => 2,
'key' => "Meta Name",
'value' => "Meta Value"
],
];
I will load my models meta with lazy loading:
use Metable;
protected $with = ['meta'];
You can use the collection map method for that so it should be something like this:
$result = $metaItems->map(function($meta) {
return [
'id' => $meta->id,
'key' => $meta->key,
'value' => $meta->value
];
})->values();
// then $result->toArray(); should give you the expected result

Cake3 Paginator Sort Error

I have a very simply model which I want to paginate. The pagination works but the sort links do not have any effect:
My Controller:
public $paginate = [
'limit' => 10,
'order' => [
'Properties.id' => 'asc'
],
'sortWhitelist' => [
'Properties.id',
'Properties.name',
'Properties.active'
],
];
My query:
$properties = $this->Properties->find('all')->where($options)->contain($contains)->order(['Properties.id']);
$this->set('properties', $this->paginate($properties));
My view displays 10 items per page and the links to pages/next/previous work fine. When I click the sort link:
$this->Paginator->sort('id', 'ID')
The url called is:
properties/index/3?sort=id&direction=desc
The page re-loads but the order of the data does not change.
The whitelist expects the exact field name that you are using in sort. It will not automatically prepend the primary table's name, so your whitelist should look like this:
public $paginate = [
'limit' => 10,
'order' => [
'Properties.id' => 'asc'
],
'sortWhitelist' => [
'id',
'name',
'active'
],
];
It will see "id" in the query and check that the exact field name "id" exists in the whitelist.
Also, it appears you are including an order() on your query. To allow the paginator to set the order, you should remove this clause.

Resources