Here is a workaround, but I am not sure if it is the standard way to do it, anyways:
//deleting a user who has a toy :)
Toy::find($toyId)->user()->newPivotStatementForId(Auth::id())->whereStatus(0)->delete();
//deleting a user who wants a toy :(
Toy::find($toyId)->user()->newPivotStatementForId(Auth::id())->whereStatus(1)->delete();
Regards,
Thank you for your response. I ended up using...
DB::delete('delete from toy_user where toy_id = ? AND user_id = ? AND status = 0', array($toy->id,Auth::id()));
Having to write plain SQL statements in an Eloquent based app seems a bit awkward for me. Having had a similar problem I would suggest:
foreach ($myToy->users as $u) {
if ($u->pivot->status == 1) {
$ut = UsersToys::find($u->pivot->id);
$ut->delete();
}
}
Pros:
Cons:
Deleting single records from a pivot table seems to be an overlooked (or maybe undocumented) feauture of Eloquent.
alf1995 liked this reply
I just ran into this problem as well and had to write a DB raw query. I haven't tired the newPivotStatementForId method yet but I can't imagine it's that much better.
Imagine if you had another column called "given". Now you can 3 possible types of rows with the combination of user_id, toy_id, status = 0|1 and given = 0|1. If you wanted to delete where user_id = x, toy_id = y, and status = 1, give = 1 that method would not work.
What Eloquent really needs is a way to access the pivot via a surrogate key. I believe you may be able to do it via a custom pivot model but haven't tried.
Just send the ID of the related model you want to detach like:
\Auth::user()->favourites()->detach($ad->id);
To access the id of pivot table you need to add the 'id' in withPivot when defining the relations. And then make a new model for pivot table and delete the single entry of pivot using pivot id. Here is my code ##Resource.php public function resources() { return $this->belongsToMany( 'DispatchLoad', 'resource_schedule', 'resource_id', 'load_id' )->withPivot(['id', 'start_date', 'end_date'])->withTimestamps(); } ##DispatchLoad.php public function resources() { return $this->belongsToMany( 'Resource', 'resource_schedule', 'load_id', 'resource_id' )->withPivot(['id', 'start_date', 'end_date'])->withTimestamps(); } ##Repo public function detach( array $input ) { return ResoureSchedule::find($input['pivot_id'])->delete(); //the pivot_id is set is passed from the form in a view, where all entries // of pivot tables are listed, when user clicks a row I take the pivot id // and submit the delete form }
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community