Home > Enterprise >  Call to a member function delete() on bool on Destroy method
Call to a member function delete() on bool on Destroy method

Time:09-21

I got this error: Call to a member function delete() on bool

Out of my code, which is:

public function destroy($id){
    $user= Auth::user();
    $descuento = Descuento::with('ventas')->where('id',$id)->first();

    foreach( $descuento as $descuentos ) {
        if( isset($descuentos->ventas->descuento_id) ) {
            return response()->json(['message' => 'No es posible eliminar el descuento ya que fue utilizado'], 500);
        } else {
            $descuentos->delete();
        }
}

Does anyone knows why I'm getting this error? I've been struggling all day because of this.

CodePudding user response:

I assume that ventas is a relationship of descuento. If that's the case and you are looking that descuento must has no ventas related in order to be deleteable, then you could make your code clean by doing this:

public function destroy($id){
    $descuento = Descuento::whereDoesntHave('ventas')->where('id', $id)->firstOrFail();
    $descuento->delete();
}

firstOrFail() will throw a 404 exception if descuento has a venta related, otherwise deletion will proceed.

BTW, is a good practice to use english names, Laravel usually maps everything by looking for nouns names (Relationships, Policies, etc)

CodePudding user response:

Your code should look like this

<?php    
public function destroy($id){
$user= Auth::user();
$descuento = Descuento::with('ventas')->where('id',$id)->first();

if(!empty($descuento)){
  if(!empty($descuento->ventas->descuento_id) ) {
    return response()->json(['message' => 'No es posible eliminar el descuento ya que fue utilizado'], 500);
  } else {
    $descuento->delete();
  }
}
  • Related