I'm developing with DataTables in Laravel and trying to make an object manually using collect() to create a collection. When I push the collection into the DataTable, there is something wrong, and I can't call my object with this $object->attribute.
After I get the error with that, I already tried to call an attribute with $object['attribute'], and it works well.
Can someone give me insight about the differences and how I can convert $object['attribute'] into $object->attribute?
This is my query to create object
$result = collect();
$item = collect([
'row' => ($key+1),
'item_id' => $value->uid,
'item' => $value->nama_item,
'sub_kategori' => $value->sub_jenis_item->sub_jenis_item,
'kategori' => $value->jenis_item->jenis_item,
'gudang_id' => $id_gudang
]);
$result->push($item);
Accessing $object['attribute'] means $object is an array and accessing $object->attribute means $object is an object.
To convert array to object:
$object = (object) $object;
Additionally, to convert object to array:
$object = (array) $object;
DataTables calls internally toArray() on the collection items when you build the table. This happens during transformation of the data. It will also flatten nested objects (e.g. loaded Eloquent relations in case of an EloquentDataTable) into an array with depth 1 (per row of the table).
You can try the following way,
$result = collect();
$item = collect([
'row' => ($key+1),
'item_id' => $value->uid,
'item' => $value->nama_item,
'sub_kategori' => $value->sub_jenis_item->sub_jenis_item,
'kategori' => $value->jenis_item->jenis_item,
'gudang_id' => $id_gudang
]
);
$result->push($item);
$resultObj = json_decode($result);
foreach($resultObj as $obj){
echo $obj->row;
}
Related
Does Laravel have a collection method that does the same thing as ->put() but does not mutate the original collection?
What I'm looking for:
<?php
$collection = collect(['key' => 'value']);
$new = $collection->putProperly('another', 'pair');
$collection // => ['key' => 'value']
$new // => ['key' => 'value', 'another' => 'pair']
I already know I can do this:
$new = $collection->merge(['another' => 'pair'])
There is no such method as seen in the list of available methods on the official doc but you can achieve the desired result easily by using the clone keyword like this:
$new = (clone $collection)->put('another', 'pair');
Keep in mind that clone performs a shallow copy, therefore be careful if your collection contains objects which you also want to clone.
I am using PHP 7.1.33 and Laravel Framework 5.8.36.
I am getting receiving data from a database row-by-row and I am creating a model using updateOrCreate() like the following:
foreach ($arr as $v) {
$product = new Product();
$product->name = $v['name'];
$product->url = $v['url'];
$product->price = $v['price'];
// save
$matchThese = ['name' => $name, 'url' => $url];
$product->updateOrCreate($matchThese);
}
However, nothing gets created.
Any suggestions what I am doing wrong?
I appreciate your replies!
updateOrCreate takes 2 parameters ($attributes, $values).
$attributes is an array containing key-value pairs which will basically be used for where clauses i.e. it will check the database for the attributes passed in this array.
$values is an array containing key-value pairs of what to update in the database.
If it can't find a row in the database matching the first array it will combine the values in the arrays to create a new row.
To achieve what you're after you can do:
Product::updateOrCreate(
['name' => $v['name'], 'url' => $v['url']],
['price' => $v['price']]
);
Try this way
Product::updateOrCreate(
['name' => $name, 'url' => $url],
['price' => v['price']],
)
First parameter is for search the register.
Second parameter set new values.
For more information, you can read Eloquent: Getting Started - Documentation
I am trying to loop through all the properties of the $entity variable on the beforeSave() method.
debug($entity) returns:
object(App\Model\Entity\Student) {
'id' => (int) 5690,
'institution_id' => (int) 35,
'contact_id' => null,
'id_number' => '0000000000',
....
However, when I try to look through the object, using
foreach ($entity as $key => $value) {
debug($key);
debug($value);
}
the foreach loop does not even run. I investigate by debug(count($entity)), and it returns 1.
How can I loop through the properties of my entity?
Any help is appreciated. Thank you.
To get a list of accessible and non-static properties of an object, use function get_object_vars.
I would also check if the $entity object is not actually an array containing a single entity object.
I have used laravel 5.6 and used the updateOrCreate model to add or update some data.
But I need to get all the values which changed
$q=Userssub::updateOrCreate(
['userid' => $uid ],
['model' => $model]
);
and the result shows like in this image
How can I get the changes array?
I tried to get it with
$u->changes
and
$u->changes->toarray()
but both return null.
What can I do to get the changed values?
Eloquent models have two protected arrays, $original and $changes, which contain the attributes as they were when fetched from storage and the attrbirutes which have been modified, respectively.
So you can use getOriginal() and getChanges() and compare the differences.
$model = Model::createOrUpdate([...]);
// wasRecentlyCreated is a boolean indicating if the model was inserted during the current request lifecycle.
if (!$model->wasRecentlyCreated) {
$changes = $model->getChanges();
}
This creates an array which will contain the original attribute value and what it was changed to:
if (!$model->wasRecentlyCreated) {
$original = $model->getOriginal();
$changes = [];
foreach ($model->getChanges() as $key => $value) {
$changes[$key] = [
'original' => $original[$key],
'changes' => $value,
];
}
}
e.g.
(
[first_name] => [
[original] => Kevinn
[changes] => Kevin
]
[website] => [
[original] => google.com
[changes] => google.ca
]
)
$jokes = $collection->find();
How do I convert $jokes into an array?
You can use PHP's iterator_to_array function, as suggested in example 1 of the MongoCursor docs:
$jokes = $collection->find();
$jokesArray = iterator_to_array($jokes);
iterator_to_array is not working for nesting more than 2 levels,
Using typeMap you can convert root and its document to array, It will work for any level of nesting
findOne($filter,$options)
$options = ["typeMap" => ['root' => 'array', 'document' => 'array']];
$collection->findOne(['myId' => $id ], $options); // returns array
find($filter,$options)
$options = ["typeMap" => ['root' => 'array', 'document' => 'array']];
$collection->find(['myId' => $id ], $options)->toArray();
As a side note to Chris's answer:
array iterator_to_array ( Traversable $iterator [, bool $use_keys =
true ] )
Pay attention to the optional second parameter, if it's set to true (default), the final array will be indexed using the "_id" field from each document.
If you applied a sort in the mongo query, the final array might not be what you expected, meaning that the sort order will not be preserved (unless you set the $use_keys parameter to false)
iterator_to_array() forces the driver to load all of the results into memory, so do not do this for result sets that are larger than memory!
use this
$jokes = $collection->find();
foreach ($jokes as $joke) {
var_dump($joke);
}
a lot easier:
findeOne()->getArrayCopy();
as mentioned before: beware from loading large resultsets and convert them to an array
you can also set your preferences with the typeMap option
'typeMap' =>[
'document' => 'array',
'root' => 'array'
]
find() basically returns MongoDB cursor http://www.php.net/manual/en/mongocollection.find.php
this should work for your case
$cursor = $collection->find();
foreach($cursor as $jokes) {
print_r($jokes);
}
in case if someone came to here, you can also use toArray method.
(mongodb >=1.0.0)
MongoDB\Driver\Cursor::toArray — Returns an array containing all
results for this cursor
$jokes = $collection->find()->toArray();
or :
$jokes = $collection->find();
$jokesArray = $jokes->toArray();