I have the following collection
$collection = collect([
['id' => 1, 'name' => 'Design'],
['id' => 2, 'name' => 'Art'],
['id' => 3, 'name' => 'Comms'],
['id' => 2, 'name' => 'Art'],
['id' => 3, 'name' => 'Comms'],
['id' => 3, 'name' => 'Comms'],
]);
I want only unique items in the collection and the collection should be sorted by number of duplicates. So an item which has most number of duplicates must appear on top as follows
$collection = collect([
['id' => 3, 'name' => 'Comms'],
['id' => 2, 'name' => 'Art'],
['id' => 1, 'name' => 'Design'],
]);
I can remove duplicates using unique method but cannot find a want to sort them.
You can do it with mapWithKeys()
https://laravel.com/docs/8.x/collections#method-mapwithkeys
$collection = $collection->groupBy('id')->mapWithKeys(function (Collection $row) {
return [$row->count() => $row->first()];
})->sortKeysDesc();
Related
$sql = DB::table('laravel_products')
->insert(array(
'name' => $name,
'price' => $price,
'qty' => $qty,
'description' => $description,
'uruu' => $uruu,
'garage' => $garage,
'duureg' => $duureg,
'tagt' => $tagt,
'talbai' => $talbai,
'haalga' => $haalga,
'tsonh' => $tsonh,
'shal' => $shal,
'tsonhtoo' => $ttsonh,
'hdawhar' => $bdawhar,
'lizing' => $lizing,
'utas' => $utas,
'email' => $email,
'hereg' => $hereg,
'bairshil' => $bairshil,
'bairlal' => $bairlal,
'ashig' => $ashigon,
'zahi' => $zahi,
'image' => $data
));
$lastInsertedID = $sql->lastInsertId();
When I try to insert its responses:
"Call to a member function lastInsertId() on bool"
I used insertGetId but its cant save multiple rows of pictures on mysql.
If you want to get the last inserted ID like that you can call that method on the PDO instance directly:
$id = DB::getPdo()->lastInsertId();
If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:
$id = DB::table('users')->insertGetId(
['email' => 'john#example.com', 'votes' => 0]
);
from : https://laravel.com/docs/5.8/queries#inserts
$data = new LaravelProducts(); //LaravelProducts is your Model Name
$data->name= $name; //here 'name' is your column name
$data->price= $price; //here 'price' is your column name
$data->qty= $qty; //here 'qty' is your column name
$data->description= $description; //here 'description' is your column name
..........
..........
$data->image= $image; //here 'image' is your column name
$data->save();
$lastInsertedId = $data->id;
You don't have to write a new query to collect last inserted id from database.
$laravel_product = DB::table('laravel_products')
->insertGetId( array(
'name' => $name,
'price' => $price,
'qty' => $qty,
'description' => $description,
'uruu' => $uruu,
'garage' => $garage,
'duureg' => $duureg,
'tagt' => $tagt,
'talbai' => $talbai,
'haalga' => $haalga,
'tsonh' => $tsonh,
'shal' => $shal,
'tsonhtoo' => $ttsonh,
'hdawhar' => $bdawhar,
'lizing' => $lizing,
'utas' => $utas,
'email' => $email,
'hereg' => $hereg,
'bairshil' => $bairshil,
'bairlal' => $bairlal,
'ashig' => $ashigon,
'zahi' => $zahi,
'image' => $data
)
);
foreach ($filenamesToSave as $filename) {
DB::insert('INSERT INTO laravel_products_images ( product_id, filename ) VALUES ( ?, ? )',[$laravel_product->id, $filename]);
return view('createproduct');
} // Foreach Closing
// Echo your inserted ID Like Below
echo $laravel_product->id;
It should be 100% working for you.
I'm trying to use Laravel collections for a simple case. I'm building a collection of furniture items and I would like to amend the item lines with additional information afterwards :
$collection = collect([
['name' => 'Desk', 'color' => 'Black'],
['name' => 'Chair', 'color' => 'Black'],
['name' => 'Bookcase', 'color' => 'Red'],
]);
I would like to add a 'stock_value' field for some items, based on the item key 'name' (for instance). In the end, I would like the collection to become something like :
['name' => 'Desk', 'color' => 'Black', 'stock_value' => 4],
['name' => 'Chair', 'color' => 'Black'],
['name' => 'Bookcase', 'color' => 'Red', 'stock_value' => 9]
I don't know how to achieve that. Any help would be greatly appreciated.
$stockValue = 9;
return $collection->transform(function ($array) use ($stockValue) {
if ($array['name'] === 'Desk') {
$array['stock_value'] = $stockValue;
}
return $array;
});
You may use transform to modify your collection.
i was finding method for fetching item in collection by specific key and value, and i have found one which is where(),
But i also want to delete that item after fetching it from original collection, but i couldn't find any method which can do both.
i have seen pull() method but it fetches by key and removes that column from collection but i want to remove particular item only.
I have looked in collection doc, but couldn't find any native method so i am using 2 method to achieve that need, the code is as below:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]);
$filtered_items = $collection->where('price', 100);
$filtered_collection = $collection->whereNotIn('price', [100]);
i am thinking that above 2 method will be little overhead if i can accomplish it in one method, so i am looking for other solutions guys, thanks beforehand your answers.
You need this one https://laravel.com/docs/5.5/collections#method-partition
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]);
$filtered_items = $collection->where('price', 100);
list($neededCollection, $filteredCollection) = $collection->partition(function ($i) {
return $i['price'] == 100;
});
dd($neededCollection, $filteredCollection);
result like this
I saw the example of laravel, but i dont understand how do it work.
for this example:
$collection = collect([
[
'name' => 'John',
'department' => 'Sales',
'email' => 'john#example.com'
],
[
'name' => 'Jane',
'department' => 'Marketing',
'email' => 'jane#example.com'
]
]);
$keyed = $collection->mapWithKeys(function ($item) {
return [$item['email'] => $item['name']];
});
$keyed->all();
someone can explain detail of it?
$collection = collect([
[
'name' => 'John',
'department' => 'Sales',
'email' => 'john#example.com'
],
[
'name' => 'Jane',
'department' => 'Marketing',
'email' => 'jane#example.com'
]
]);
$keyed = $collection->mapWithKeys(function ($item) {
//this line takes one array of collection object in item array and make a key of its email and store name on that email key
return [$item['email'] => $item['name']];
});
$keyed->all();
I'm trying to make a collection from some arrays of data:
$myCollection = collect(
['product_id' => 1, 'price' => 200, 'discount' => '50'],
['product_id' => 2, 'price' => 400, 'discount' => '50']
);
When I loop out I would like to do:
foreach ($myCollection as $product) {
echo $product->price;
echo $product->discount;
}
But the underlying elements appear to still be in an arrays format, how can I achieve the above output?
If you want the inner arrays to be a collection, then you can do so as follows:
$myCollection = collect([
['product_id' => 1, 'price' => 200, 'discount' => '50'],
['product_id' => 2, 'price' => 400, 'discount' => '50']
])->map(function($row) {
return collect($row);
});
If you want the inner arrays to be objects, then you can do as follows:
$myCollection = collect([
['product_id' => 1, 'price' => 200, 'discount' => '50'],
['product_id' => 2, 'price' => 400, 'discount' => '50']
])->map(function($row) {
return (object) $row;
});
You can also iterate over each of the results...
$myCollection = collect([
['product_id' => 1, 'price' => 200, 'discount' => '50'],
['product_id' => 2, 'price' => 400, 'discount' => '50']
])->map(function($row) {
return (object) $row;
})->each(function($row) {
echo sprintf('ProductId: %d, Price: %d, Discount: %s'.PHP_EOL, $row->product_id, $row->price, $row->discount);
});
Output:
ProductId: 1, Price: 200, Discount: 50
ProductId: 2, Price: 400, Discount: 50
Simple as you are getting a collection of an associative arrays because you are collecting arrays elements, so the collection helper doesn't want to modify it in case you need it as array.
Knowing this, if you want to collect objects you should pass an element of object type.
You can cast object data type into the array, like this:
$myCollection = collect( (object) array(
(object) ['product_id' => 1, 'price' => 200, 'discount' => '50'],
(object) ['product_id' => 2, 'price' => 400, 'discount' => '50'])
);
Then you have a collection of objects !
Function collect() takes array of elements. You can fix your code also by enclosing all the elements into [] and then converting Collection elements to objects instead of leaving them to be arrays
$myCollection = collect([
(object)(['product_id' => 1, 'price' => 200, 'discount' => '50']),
(object)(['product_id' => 2, 'price' => 400, 'discount' => '50'])
]
);
foreach ($myCollection as $product) {
echo $product->price;
echo $product->discount;
}
There's a syntax error in your collection definition:
$myCollection = collect([
['product_id' => 1, 'price' => 200, 'discount' => '50'],
['product_id' => 2, 'price' => 400, 'discount' => '50']
]);
Also, since you're using a Collection, you no longer need to use a foreach loop:
$myCollection->each(function ($item) {
echo $item['price'];
})