Luis Coutinho
Luis Coutinho

Reputation: 41

Detach Laravel 5.3

After some hours debugging and trying to solve a problem, I don't found the solution. So, I hope that you can help me.

I have this little piece of code:

$removed = false;
if ($store->persons->contains($person)) {
    $store->persons()->detach($person);
    $removed = true;
}

var_dump($removed);

My problem is that I can't understand why $remove is "false" always. If I comment the line $store->persons()->detach($person);, everything works as expected and $removed will be "true". I can't understand why this is happening, but I hope that you can help me.

EDIT

public function removePerson(Request $request, $storeId, $personId)
{
    $store = Store::findOrFail($storeId);
    $person = Cashier::findOrFail($personId);

    $removed = false;
    if ($store->persons->contains($person)) {
        $store->persons()->detach($person);
        $removed = true;
    }

    return response()->json([
        'removed' => $removed,
    ]);
}

Thank you.

Upvotes: 0

Views: 669

Answers (1)

Sagar Rabadiya
Sagar Rabadiya

Reputation: 4321

detacth/attach method don't take full model as argument, instead they both need id of the related model so in your case you need to pass id in detach method for ex.

public function removePerson(Request $request, $storeId, $personId)
{
    $store = Store::findOrFail($storeId);
    $person = Cashier::findOrFail($personId);

    $removed = false;
    if ($store->persons->contains($person)) {
        $store->persons()->detach($person->id); // or $personId which ever
        $removed = true;
    }

    return response()->json([
        'removed' => $removed,
    ]);
}

Upvotes: 1

Related Questions