askedio / laravel-soft-cascade Goto Github PK
View Code? Open in Web Editor NEWCascade Delete & Restore when using Laravel SoftDeletes
Home Page: https://medium.com/asked-io/cascading-softdeletes-with-laravel-5-a1a9335a5b4d
License: MIT License
Cascade Delete & Restore when using Laravel SoftDeletes
Home Page: https://medium.com/asked-io/cascading-softdeletes-with-laravel-5-a1a9335a5b4d
License: MIT License
Using soft cascade on a BelongsTo
relationship throws a SoftCascadeLogicException
. In the example below when soft deleting ModelA
, ModelB
should be soft deleted and subsequently ModelC
. ModelA
removing ModelB
is not a problem, but cascading ModelC
from ModelB
generates an invalid query. ModelB
in this case acts like a kind of enriched pivot model.
SQLSTATE[42S22]: Column not found: 1054 Unknown column
select count(*) as aggregate
from `models_c`
where `models_b`.`model_c_id` in (?)
and `models_c`.`deleted_at` is null
See code example.
class ModelA extends Model
{
use SoftDeletes;
use SoftCascadeTrait;
protected $table = 'models_a';
protected $softCascade = [
'modelB',
];
public function modelB(): HasMany
{
return $this->hasMany(ModelB::class, 'model_a_id');
}
}
class ModelB extends Model
{
use SoftDeletes;
use SoftCascadeTrait;
protected $table = 'models_b';
protected $softCascade = [
'modelC',
];
public function modelA(): BelongsTo
{
return $this->belongsTo(ModelA::class, 'model_a_id');
}
public function modelC(): BelongsTo
{
return $this->belongsTo(ModelC::class, 'model_c_id');
}
}
class ModelC extends Model
{
use SoftDeletes;
use SoftCascadeTrait;
protected $table = 'models_c';
}
$modelA = new ModelA();
$modelA->save();
$modelC = new ModelC();
$modelC->save();
$modelB = new ModelB();
$modelB->modelA->associate($modelA);
$modelB->modelC->associate($modelC);
$modelB->save();
$modelA->delete();
Hi.
Cannot install this package on L5.7 due to composer requirements "5.6.*".
Can you update to L5.7?
Thanks in advance
On belongs to many relation, a bad pivot key name is used to find the good relation
Changing getQualifiedForeignPivotKeyName
with getRelatedPivotKeyName
works for me :)
I get many exceptions because of soft cascade for the last months. I catch them using Sentry. Here is an example:
Sentry example
In the App\Models\Lead
I have:
use SoftDeletes, SoftCascadeTrait;
protected $softCascade = ['someRelationship'];
public function someRelationship(): HasMany
{
...
}
laravel/framework 5.8.29
askedio/laravel-soft-cascade 5.8.0
I have an /admin
dashboard to control what to hide and what to show for the frontend.
My Job
model's relationships:
Job
-> belongsTo: Category
Job
-> belongsTo: Company
In my admin/jobs/index.blade
view I list the jobs with links to $job->company
and $job->category
, but because I soft deleted a company or category, it gives route error.
How do I query for a trashed relationship so I can still see it?
I'm querying for jobs correctly, but the relationships aren't found, is there a way to include them even if soft deleted?
/**
* Display a listing of the resource.
*
* @return \Illuminate\View\View
*/
public function index() : View
{
$jobs = Job::latest()->withTrashed()->paginate(20);
return view('admin.jobs.index')->with(compact('jobs'));
}
No rush. And thanks for this package, works great!! 😎
I am using laravel 5.4 and need to perform a soft delete through a pivot table, ie I have a pivot table which, when deleted, needs to cascade the delete to another table.
When executing 'delete', the pivot table is 'deleted', but nothing happens to the other table. Any idea?
table that will have the cascaded delete:
protected $softCascade = ['category'];
delete statement
CompanyService::findOrFail(11)->delete();
NOTE: In my migrations I did not use onCascade, is this a problem?
Thank you in advance and sorry for my English.
laravel/framework#20869 (comment)
Need to rename variables to support 5.5 changes.
Hello,
laravel 6.0 is out now,
do you plan to support it ?
thanks.
Hey.
I really like the idea of the package and tried using it but I stubmled upon the issue where when I try and soft delete an object I get the following error:
ErrorException in CascadeDeleteListener.php line 18: Missing argument 2 for Askedio\SoftCascade\Listeners\CascadeDeleteListener::handle()
Here is part of the stack trace:
in CascadeDeleteListener.php line 18
at HandleExceptions->handleError('2', 'Missing argument 2 for Askedio\SoftCascade\Listeners\CascadeDeleteListener::handle()', '/var/www/html/arabian/vendor/askedio/laravel5-soft-cascade/src/Listeners/CascadeDeleteListener.php', '18', array('event' => object(Pilot))) in CascadeDeleteListener.php line 18
at CascadeDeleteListener->handle(object(Pilot))
at call_user_func_array(array(object(CascadeDeleteListener), 'handle'), array(object(Pilot))) in Dispatcher.php line 349
at Dispatcher->Illuminate\Events{closure}(object(Pilot))
at call_user_func_array(object(Closure), array(object(Pilot))) in Dispatcher.php line 221
at Dispatcher->fire('eloquent.deleting: App\Pilot', object(Pilot), true) in Dispatcher.php line 164
at Dispatcher->until('eloquent.deleting: App\Pilot', object(Pilot)) in Model.php line 1663
at Model->fireModelEvent('deleting') in Model.php line 1104
at Model->delete(array()) in EntrustUserTrait.php line 34
at Pilot->delete() in PilotController.php line 220
at PilotController->destroy('1089')
at call_user_func_array(array(object(PilotController), 'destroy'), array('pilot' => '1089')) in Controller.php line 55
at Controller->callAction('destroy', array('pilot' => '1089')) in ControllerDispatcher.php line 44
at ControllerDispatcher->dispatch(object(Route), object(PilotController), 'destroy') in Route.php line 190
I have the deleted_at columns in both tables and here are the models.
Pilot.php
<?php
namespace App;
use Cmgmyr\Messenger\Traits\Messagable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Venturecraft\Revisionable\RevisionableTrait;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use \Askedio\SoftCascade\Traits\SoftCascadeTrait;
class Pilot extends Authenticatable {
use SoftDeletes, Notifiable, EntrustUserTrait, RevisionableTrait, Messagable, SoftCascadeTrait {
SoftDeletes::restore insteadof EntrustUserTrait;
}
protected $softCascade = ['pireps'];
protected $table = 'pilots';
#### ..........
public function pireps () {
return $this->hasMany(PIREP::class);
}
PIREP.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use \Askedio\SoftCascade\Traits\SoftCascadeTrait;
class PIREP extends Model {
use SoftDeletes, SoftCascadeTrait;
public function pilot () {
return $this->belongsTo(Pilot::class);
}
How I am trying to delete the Pilot object (and the associated PIREPs)
PilotController.php
public function destroy($id) {
$pilot = Pilot::findOrFail($id);
if (!$pilot) {
Flash::error('There is no pilot with that ID.');
return redirect()->back();
}
$pilot->delete();
Flash::success('The pilot has been deleted.');
return redirect()->route('admin.pilots.index');
}
Can you provide some ideas?
To add, it seems when I tried to revert back and delete everything from the model that has to do with the package I still get the error upon trying to delete, even though I didn't specify $softCascade or have the use SoftCascadeTrait. Only after I comment out the provider from app.php the error stops displaying.
I ran across this in a comment earlier:
https://github.com/jarektkaczyk/eloquent-cascade/
It would be nice if we can support the QB too, if we don't already.
Post -> comments (3).
One comment is already deleted.
Post::first()->delete();
After call this all 3 comments has deleted_at set in one moment.
Is this how it should works?
Restoring post cause restore all 3 comments, i think should only 2 comment which was deleted with post.
Hello,
First of all, thank you for this package. I'm getting an error when I try to soft delete a relation that has a composite keys. I'm using this trait for composite keys.
The returned error is: "stripos() expects parameter 1 to be string, array given". That's because in my model my primary key looks like: protected $primaryKey = [ 'column1', 'column2' ];
. Therefore it isn't a string but an array.
Any idea on how to resolve this? Thanks for your feedback!
I understand that this package makes a logical deletion of the models that are related to this, if I want to restore the deleted model, it automatically restores the related models?
I have the following models:
https://gist.github.com/GDanielRG/2fa94cce20898439943e6ac7813c07fd
When I run $user->delete(); it gives the following error:
Askedio\SoftCascade\Exceptions\SoftCascadeLogicException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ticket_events.' in 'where clause' (SQL: select count(*) as aggregate from ticket_events
where ticket_events
.`` in (o9ractuoan, 12m8237uvk, 16p1b650kk, 89508qr3k9, o0tr8hdnvr))'
I realized that the error goes away if I remove the 'ticketEventable' relation from the $softCascade array in the TicketEvent.php
so if I comment out the following line (from TicketEvent.php):
protected $softCascade = ['ticketEventable'];
the delete goes through correctly, it deletes the user, then deletes the tickets related to the user, also the ticket events of the user and the ticket events of the tickets of the user, but the problem is that since I comented that line Im not getting the models from the ticketEventable relationship deleted :/
Any help would be much appreciated
I would like to update an existing app, but, i dont really know what is the process for checking L5.5 compatibility.
If you don't have time for that, could you give me an idea of how to help you?
I'm unable to pull version 5.8.0 via composer
Packagist showing latest version is 5.7.0, repo is showing the latest package as 5.8.0
https://packagist.org/packages/askedio/laravel-soft-cascade
I get the following error when trying to delete a record. The model in question does not use SoftCascade. However, there two other models higher in the hierarchy that do. For example, I have Project => Expedition => Subject relationships where if a Project or Expedition is deleted, soft cascade handles deleting all the subjects. The subjects are in MongoDB and use jenssegers/laravel-mongodb package.
I've not had an issue with this until recently. Has something changed?
[2018-02-04 00:27:15] local.ERROR: Call to a member function beginTransaction() on null {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Call to a member function beginTransaction() on null at /home/vagrant/sites/biospex/production/vendor/laravel/framework/src/Illuminate/Database/Concerns/ManagesTransactions.php:108)
[stacktrace]
#0 /home/vagrant/sites/biospex/production/vendor/laravel/framework/src/Illuminate/Database/Concerns/ManagesTransactions.php(92): Illuminate\\Database\\Connection->createTransaction()
#1 /home/vagrant/sites/biospex/production/vendor/askedio/laravel5-soft-cascade/src/SoftCascade.php(65): Illuminate\\Database\\Connection->beginTransaction()
#2 /home/vagrant/sites/biospex/production/vendor/askedio/laravel5-soft-cascade/src/SoftCascade.php(35): Askedio\\SoftCascade\\SoftCascade->run(Object(Illuminate\\Support\\Collection))
#3 /home/vagrant/sites/biospex/production/vendor/askedio/laravel5-soft-cascade/src/Listeners/CascadeDeleteListener.php(20): Askedio\\SoftCascade\\SoftCascade->cascade(Array, 'delete')
#4 [internal function]: Askedio\\SoftCascade\\Listeners\\CascadeDeleteListener->handle('eloquent.deleti...', Array)
#5 /home/vagrant/sites/biospex/production/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(365): call_user_func(Array, 'eloquent.deleti...', Array)
#6 /home/vagrant/sites/biospex/production/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(200): Illuminate\\Events\\Dispatcher->Illuminate\\Events\\{closure}('eloquent.deleti...', Array)
#7 /home/vagrant/sites/biospex/production/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(160): Illuminate\\Events\\Dispatcher->dispatch('eloquent.deleti...', Array, true)
#8 /home/vagrant/sites/biospex/production/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasEvents.php(148): Illuminate\\Events\\Dispatcher->until('eloquent.deleti...', Object(App\\Models\\Subject))
#9 /home/vagrant/sites/biospex/production/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(776): Illuminate\\Database\\Eloquent\\Model->fireModelEvent('deleting')
#10 /home/vagrant/sites/biospex/production/app/Console/Commands/TestAppCommand.php(46): Illuminate\\Database\\Eloquent\\Model->delete()
#11 [internal function]: App\\Console\\Commands\\TestAppCommand->handle()
user.php
namespace App;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use \Askedio\SoftCascade\Traits\SoftCascadeTrait;
class User extends Authenticatable
{
use Notifiable, SoftDeletes, SoftCascadeTrait;
protected $softCascade = ['offers'];
public function offers()
{
return $this->hasMany('App\Offer');
}
offer.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Offer extends Model
{
use SoftDeletes;
}
UsersController.php
<?php
namespace App\Http\Controllers;
use App\User;
class UsersController extends Controller
{
public function delete($id)
{
try {
User::where('id', $id)->delete();
} catch (\Exception $e) {
return response()->json([
'message' => $e->getMessage(),
], 403);
}
}
}
offers table
Schema::create('offers', function (Blueprint $table) {
$table->id();
$table->bigInteger('user_id')->unsigned();
$table->softDeletes();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
});
Hi!,
I have a "Issuer" model with a one-to-many relationship with "Branch", "Receivers", "Product", if I delete a "Issuer" the related models are correctly deleted in cascade, but, if I delete a "Branch" (which has a one-to-many relationship with "Phone", "Series") "Branch", "Phone", "Series" are deleted because they are dependent on "Branch" and also deletes the "Issuer" model, although "Issuer" and "Branch" have a relationship, how can I avoid that by eliminating a "Branch" the "Issuer" or some other relationship is not deleted?
any idea why am i getting this error?
PHP error: Undefined index: class in /**/vendor/askedio/laravel5-soft-cascade/src/Listeners/CascadeQueryListener.php on line 20
Reduce these variable names to less then 20 chars.
I revoked the key due to:
You may have recently heard from Travis CI (https://blog.travis-ci.com/2017-05-08-security-advisory) about a security incident involving a disclosure of your GitHub.com OAuth tokens. We want to follow up and give you some more information.
Will need to update this later.
thank you beforehand !
i have defined all the process which you have told but still it is not cascading the softdelete
i have parent model
Is there any way to forceDelete cascade with this package ? I mean I have several model using SoftDelete and your very useful package but I would also like to be able to forceDelete and cascadin forceDelete on Relations.
Many thanks in advance for your answer.
Hello,
If you do a delete with a query like this:
User::whereId(1)->delete();
Eloquent will perform the soft delete but doesn't trigger an event. Taylor said that's expected behavior, so that probably won't be fixed. That means the cascade will not work for query deletes.
Here is a failing test that illustrates the problem:
public function testDeleteWhenQuery()
{
$this->createUserRaw();
$this->createUserRaw();
User::whereId(1)->delete();
$this->assertEquals(2, User::withTrashed()->count());
$this->assertEquals(1, User::count());
$this->assertEquals(2, Profiles::withTrashed()->count());
$this->assertEquals(1, Profiles::count(), 'The delete should cascade');
}
If you look at how Laravel does it for the primary model, they register a callback with the Builder. It seems like hooking in there would allow cascading on queries too.
This would clean up nearly all of the issues.
I am trying to install it on 5.2.30 but doesn't let me
In this example, i have both User and Profile models. User hasOne Profile. Both models are using soft deletes. Soft Cascade is configured on User model.
The package functionality is working as expected, but, i'm wondering if the following behavior should be expected:
$profiles = Profile::withTrashed()->get();
I can have all my profiles, including soft deleted ones with the query above, but it's not retrieving the related user, since it's soft deleted.
What do you think about it? Should this package be responsible to handle this and add the withTrashed scope on the related model as well?
Similar to this: https://stackoverflow.com/a/25875054/3948755
this lib is working fine, so I have to permanent delete records from database... is it possible in cascade way?
Hello,
laravel 5.5
latest version of the package.
i am getting an error using the package:
"App\Model\System\Focus 'contracts' is not an instance of Illuminate\Database\Eloquent\Relations\Relation."
Contract model:
class Contract extends Model
{
use ObservantTrait;
use \Askedio\SoftCascade\Traits\SoftCascadeTrait;
protected $softCascade = ['focus'];
public function focus()
{
return $this->belongsToMany(Focus::class, 'tbl_prm_ctr_focus_assoc', 'prm_contract_id', '
prm_ctr_focus_id');
}
}
Focus:
class Focus extends Model
{
use ObservantTrait;
use SoftDeletes;
use \Askedio\SoftCascade\Traits\SoftCascadeTrait;
protected $softCascade = ['contracts'];
public function contracts() {
$this->belongsToMany(Contract::class, 'tbl_prm_ctr_focus_assoc', 'prm_contract_id', 'prm_ctr_focus_id');
}
}
I get this error message when i try to delete a focus.
Can this be related to the issue with belongsToMany?
In my system a Student is a User. After the following code a user was actually deleted. However, it took the students id and used it on the user table, thus, deleting the wrong user.
This is my controller's method
try {
DB::transaction(function () use ($id) {
Student::findOrFail($id)->delete();
}, 5);
return redirect()->action('StudentController@index');
} catch (ModelNotFoundException $exception) {
return redirect()->action('StudentController@index');
}
This is my Student class
<?php
namespace App;
use Askedio\SoftCascade\Traits\SoftCascadeTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Student extends Model
{
use SoftCascadeTrait;
use SoftDeletes;
protected $softCascade = ['user'];
protected $dates = ['deleted_at'];
public function user()
{
return $this->belongsTo('App\User');
}
}
Am I missing anything?
does not record auditable
Install owen-it/laravel-auditing:10.0.0
Create Subject -> Topic
Delete Subject, only record auditable data for Subject no for Topic and similar for forceDeleted
Sometimes i need to use delete or restore without cascade, sometimes with. How to do that ? Do i need two models on working with cascade mode and other without ?
Does the package have set null support? I'm trying to use it with @setnull
but it won't work.
Hi, first than all thanks for this package, it's really helpful,
i use Awobaz Comboships to make relations between models with more than one colunm, like this:
public function jobs()
{
return $this->hasMany('App\UserJob', ['user_id', 'client_id', 'destination_id'], ['user_id', 'client_id', 'destination_id']);
}
that way i can relate models specifically with more terms, i tried to use softdeletes with this, but nothing happened... any ideas? hints?
This is the model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class UserClientDestination extends Model
{
use SoftDeletes;
use \Awobaz\Compoships\Compoships;
use \Askedio\SoftCascade\Traits\SoftCascadeTrait;
protected $softCascade = ['jobs'];
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'user_id',
'client_id',
'destination_id',
'name',
'sub_name',
'zone_id',
];
public function jobs()
{
return $this->hasMany('App\UserJob', ['user_id', 'client_id', 'destination_id'], ['user_id', 'client_id', 'destination_id']);
}
}
It appears that 6.0 isn't available via Composer currently
Trying to delete a Model instance that has SoftCascadeTrait and get the following:
SoftCascadeLogicException {#750 ▼ #message: "Call to undefined method Illuminate\Database\Query\Builder::withTrashed()" #code: 0 #file: "/home/vagrant/Code/medixaid/vendor/askedio/laravel5-soft-cascade/src/SoftCascade.php" #line: 38 -previous: BadMethodCallException {#755 ▶} trace: {▼ /home/vagrant/Code/medixaid/vendor/askedio/laravel5-soft-cascade/src/SoftCascade.php:38 {▶} /home/vagrant/Code/medixaid/vendor/askedio/laravel5-soft-cascade/src/Listeners/CascadeDeleteListener.php:20 {▶} Askedio\SoftCascade\Listeners\CascadeDeleteListener->handle() {} /home/vagrant/Code/medixaid/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php:364 {▶} /home/vagrant/Code/medixaid/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php:199 {▶} /home/vagrant/Code/medixaid/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php:159 {▶} /home/vagrant/Code/medixaid/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasEvents.php:148 {▶} /home/vagrant/Code/medixaid/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:742 {▼ › › if ($this->fireModelEvent('deleting') === false) { › return false; arguments: {▶} } /home/vagrant/Code/medixaid/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:714 {▶} /home/vagrant/Code/medixaid/app/Http/Controllers/Admin/ProvidersController.php:153 {▼ › try { › Provider::destroy($id); › } arguments: {▶} }
The error disappear when I remove the SoftCascade Trait. The model has 4 relationships but the record to be deleted has no related records at the moment of the call.
Would appreciate some guidance. Many thanks in advance.
Firstly , Thanks for this Awesome Package
in fact i am using uuid in routing outside my app and id in relationships as the following example
use \Askedio\SoftCascade\Traits\SoftCascadeTrait;
protected $softCascade = ['orders'];
protected $primaryKey = 'id';
public function getKeyName()
{
return 'uuid';
}
/**
* Get all of the user's orders.
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function orders()
{
return $this->morphMany(Order::class, 'orderable', 'owner_type', 'owner_id', 'id');
}`
When i try to delete within softCascade nothing happen with relation
Note: this's not only morphMany but with all laravel relations
Any Suggest,Thanks
not install the package
Problem 1
- Conclusion: don't install askedio/laravel-soft-cascade 6.0.1
- Conclusion: don't install askedio/laravel-soft-cascade 6.0.0
- Conclusion: remove laravel/framework v5.8.14
- Installation request for askedio/laravel-soft-cascade ^6.0 -> satisfiable by askedio/laravel-soft-cascade[6.0.0, 6.0.1, 6.0.x-dev].
- Conclusion: don't install laravel/framework v5.8.14
- askedio/laravel-soft-cascade 6.0.x-dev requires illuminate/events ^6.0 -> satisfiable by illuminate/events[6.x-dev, v6.0.0, v6.0.1, v6.0.2, v6.0.3, v6.0.4, v6.1.0, v6.2.0, v6.3.0].
- don't install illuminate/events 6.x-dev|don't install laravel/framework v5.8.14
- don't install illuminate/events v6.0.0|don't install laravel/framework v5.8.14
- don't install illuminate/events v6.0.1|don't install laravel/framework v5.8.14
- don't install illuminate/events v6.0.2|don't install laravel/framework v5.8.14
- don't install illuminate/events v6.0.3|don't install laravel/framework v5.8.14
- don't install illuminate/events v6.0.4|don't install laravel/framework v5.8.14
- don't install illuminate/events v6.1.0|don't install laravel/framework v5.8.14
- don't install illuminate/events v6.2.0|don't install laravel/framework v5.8.14
- don't install illuminate/events v6.3.0|don't install laravel/framework v5.8.14
- Installation request for laravel/framework (locked at v5.8.14, required as 5.8.*) -> satisfiable by laravel/framework[v5.8.14].
composer require askedio/laravel-soft-cascade
What will happen if I have used onDelete restrict while creating a relationship. Does this softDelete will raise and restrict that record from softdeleting?
@gcphost I think we need to add an skeleton when users create new issues. It could be this information:
When a resource is restored all soft-deleted relations specified in $softCascade = ['profiles']
are also restored.
Is there any way we get make it so the package only restores the relations who were deleted in the cascade?
How about when restoring, only relations with a matching deleted_at
are restored? I admit this wouldn't be 100% perfect, but at the moment ALL cascading relations are restored, even ones deleted far in the past.
We could add this as a configuration, so users could set which behaviour they prefer. Happy to make a PR if you are interested in the idea
Laravel Tinker 2.0 isn't supported.
Update Laravel Tinker to version 2.0 and you'll get an error message.
If we define many-to-many relationship, for example User-Roles. Trait will not set soft delete timestamp on pivot table, instead exception will be thrown with message that updated_at column is ambigious. Probably because both roles and user_roles table has updated_at field.
It happens only on many-to-many relationships. I made workaround for this, and that is defining relation just for softDelete. So in the end it looks like this:
public function role()
{
return $this->belongsToMany(Role::class, 'user_role', 'user_id','role_id')->withTimestamps();
}
public function role_soft_delete()
{
return $this->hasMany(UserRole::class, 'user_id', 'id');
}
protected $softCascade = ['meal_soft_delete'];
Using this workaround it works normally.
First thank you for this great package!
As far as I can tell, when cascade-restoring a model, the updated_at column is changed which is a problem for my application. Is it a Laravel problem? Is it this package, and if so, is it the intended behaviour? And finally, is there a way to disable this behaviour?
Thank you in advance!
@gcphost I think it would be nice to rename the package from laravel5-soft-cascade to laravel-soft-cascade.
It's just a proposal.
The model events (like deleting
or deleted
) are not fired during the soft cascade (not sure if this is intended behavior).
I want to use Observers to act on the models before they are soft deleted, but they don't get called since the events are not fired.
I am taking steps to upgrade my Laravel version, so if this is already solved (in case it isn't expected behavior) in the package's 5.6 and 5.7, that would be a relief.
Thanks for your time. Awesome package, by the way!
Create an Observer for a model that is going to be cascade (soft) deleted and then (soft) delete the parent model.
Edit: typo.
ModelA.php
class ModelA extends Model
{
use SoftDeletes;
use SoftCascadeTrait;
protected $dates = ['deleted_at'];
protected $softCascade = [
'children'
];
public function children()
{
return $this->hasMany(ModelB::class);
}
}
ModelB.php
{
use SoftDeletes;
protected $dates = ['deleted_at'];
public function parent()
{
return $this->hasOne(ModelA::class);
}
}
ModelBObserver.php
class ModelBObserver
{
public function deleting(ModelB $model)
{
$model->name = 'Deleted Model';
$model->save();
}
}
In AppServiceProvider.php
public function boot()
{
...
ModelB::observe(ModelBObserver::class);
}
In a Test file:
/** @test **/
public function testEventsOnCascade()
{
$modelA = new ModelA();
$modelA->save();
$modelA->refresh();
$modelB = new ModelB();
$modelB->parent_id = $modalA->id;
$modelB->save();
$modelA->refresh();
$modelB->refresh();
$modelA->delete();
$modelB->refresh();
$this->assertEquals('Deleted Model', $modelB->name);
}
The test fails.
This is really nice package, makes life lot easier.
It will be great if also supports models that are not using SoftDeletes
There are many situations where you don't like to use SoftDeletes
for example
Blogs hasMany
Comments.
( We are not using SoftDeletes on comments
table )
Right now it throws this exception.
Illuminate\Database\Query\Builder::withTrashed()
If Update https://github.com/Askedio/laravel5-soft-cascade/blob/master/src/SoftCascade.php#L90 to
foreach ($relation->get() as $model) {
this resolves the issue, but i'm looking forward to your solution.
Thanks
ErrorException in CascadeDeleteListener.php line 18:
Missing argument 2 for Askedio\SoftCascade\Listeners\CascadeDeleteListener::handle()
I'm getting the error above when deleting a model. In debugging, I've removed all the items in the $softCascade array, so I don't think it's a Model code issue, but who knows.
I'm Laravel 5.3. Need more info?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.