0

I am making simple crud and want to delete favourite list table's columns if user_id and hymn_id matches from favourite_list table

here is my delete route:

Route::resource('fav_hymns', 'Api\favouriteController');
Route::delete('fav_hymns/{user_id}/{hymn_id}/', 'Api\favouriteController@destroy');

and my 'destroy' function in resource favouriteController

public function destroy($user_id,$hymn_id)
{

    $favourite_list = favourite_list::where('user_id','=',$user_id, 'AND', 'hymn_id', '=', $hymn_id)->delete();


    if (!$favourite_list) {
        return response()->json([
            'success' => false,
            'message' => 'Error: List not found'
        ], 400);
    }

    if ($favourite_list) {
        return response()->json([
            'success' => true
        ]);
    } else {
        return response()->json([
            'success' => false,
            'message' => 'List could not be deleted'
        ], 500);
    }
}

but the problem is, it's deleting all the columns if $user_id matches and $hymn_id (in route) doesn't even exist and doesn't even match, it is deleting all the columns.

Help would be appreciated, thanks

2 Answers 2

1

Your delete where() condition is not correct here. You should try like.

try{

 favourite_list::where('user_id', $user_id)
                            ->where('hymn_id', $hymn_id)
                            ->delete();

} catch(\Exception $e){
    return response()->json([
            'success' => false,
            'message' => 'List could not be deleted'
    ], 500);
}


 return response()->json([
     'success' => true
 ]);

Each conditions should be wrap under different where(). If you would like the SQL format... try using whereRaw().

Sign up to request clarification or add additional context in comments.

1 Comment

@NoumanNazir it seems you marked the different solution... make sure you are correct. As with that... suppose if you have 5000 records... it could loop over each record and delete one by one. So It would not be the good approach.
0

Do sth like this

public function destroy($user_id,$hymn_id)
{

    $favourite_lists =favourite_list::where('user_id', $user_id)
                            ->where('hymn_id', $hymn_id)->get();

    foreach($favourite_lists as $favourite_list)
    {
      $favourite_list->delete();
    }
    return response()->json("records deleted",200);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.