Rodri6uez
Rodri6uez

Reputation: 477

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

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.

Upvotes: 0

Views: 565

Answers (2)

Luciano
Luciano

Reputation: 2196

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)

Upvotes: 3

Rakesh Mehta
Rakesh Mehta

Reputation: 533

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();
  }
}

Upvotes: 2

Related Questions