This is the way I would do it:
public function patch(Request $request)
{
Child::whereNotIn('id', array_column($request->childs, 'id'))->delete();
Child::upsert([
$request->childs
], ['id'], ['name']);
}
If you don't want to soft delete the child you can applyforceDelete()
as below:
child::where('parent_id',Request->id)->forceDelete();
foreach($Request->childs as $item) {
if($item->id == null){
child::create['name'=>$item->name,'parent_id'=>$Request->id];
}
child::find($item->id)->update['name'=>$item->name];
}
Oh, it's big problem. I solved it for my project, but not very happy with this solution.
$parent->childs()->sync($request['childs'])
if you pass true as second value - null childs will be removed
Add this code to AppServiceProvider::boot() - it's not my code, just copy pasted from somewhere and slightly improved
HasMany::macro('sync', function (array $data, $deleting = true) {
/** @var HasMany $this */
$changes = [
'created' => [], 'deleted' => [], 'updated' => [],
];
$relatedKeyName = $this->getRelated()->getKeyName();
$current = $this->newQuery()->pluck($relatedKeyName)->all();
$castKey = function ($value) {
if (is_null($value)) {
return $value;
}
return is_numeric($value) ? (int) $value : (string) $value;
};
$castKeys = function ($keys) use ($castKey) {
return (array) array_map(function ($key) use ($castKey) {
return $castKey($key);
}, $keys);
};
$deletedKeys = array_diff($current, $castKeys(
Arr::pluck($data, $relatedKeyName))
);
if ($deleting && count($deletedKeys) > 0) {
$this->getRelated()->destroy($deletedKeys);
$changes['deleted'] = $deletedKeys;
}
$newRows = Arr::where($data, function ($row) use ($relatedKeyName) {
return Arr::get($row, $relatedKeyName) === null;
});
$updatedRows = Arr::where($data, function ($row) use ($relatedKeyName) {
return Arr::get($row, $relatedKeyName) !== null;
});
if (count($newRows) > 0) {
$newRecords = $this->createMany($newRows);
$changes['created'] = $castKeys(
$newRecords->pluck($relatedKeyName)->toArray()
);
}
foreach ($updatedRows as $row) {
$this->getRelated()->where($relatedKeyName, $castKey(Arr::get($row, $relatedKeyName)))
->update($row);
}
$changes['updated'] = $castKeys(Arr::pluck($updatedRows, $relatedKeyName));
return $changes;
});
You just need to get the ids from the database and compare
{
$childIds = child::where('parent_id',Request->id)->pluck('id')->toArray();
$flippedChildIds = array_flip($childIds);// we flip the keys and values for easy unsetting.
$childsToBeInsertedOrUpdated = [];
foreach($Request->childs as $item){
//add deleted at in case a child was deleted and need to be re activated
// if you dont want the child to be reactivated, remove "deleted_at" from both arrays
$childsToBeInsertedOrUpdated[] = ['id' => $item->id, 'name' => $item->name, 'deleted_at' => null];
//if exists, remove from the to be deleted childs
unset($flippedChildIds[$item->id]));
}
//only two request for delete and update/create (faster)
if ($flippedChildIds) {
Child::whereIn('id', array_keys($flippedChildIds))->delete();
}
if ($childsToBeInsertedOrUpdated) {
Child::upsert($childsToBeInsertedOrUpdated, ['id'], ['name', 'deleted_at']);
}
}
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
React is currently the leader in JavaScript UI frameworks. First, the Facebook developers started working on this to make their job easier. An app called Facebook Ads grew very quickly, which meant complex management and support. As a result, the team began to create a structure that would help them with efficiency. They had an early prototype before 2011, and two years later, the framework was open source and available to the public. It is currently used by many business giants: AirBNB, PayPal, Netflix, etc.
https://reactjs.org/
DBMS is a database management system. It is designed to change, search, add and delete information in the database. There are many DBMSs designed for similar purposes with different features. One of the most popular is MySQL.
It is a software tool designed to work with relational SQL databases. It is easy to learn even for site owners who are not professional programmers or administrators. MySQL DBMS also allows you to export and import data, which is convenient when moving large amounts of information.
https://www.mysql.com/
Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.