Home > database >  Why the delete query will not execute Laravel
Why the delete query will not execute Laravel

Time:02-01

Hello i am trying to make a simple delete function but its showing an error

This is the code from the controller:

public function destroy($id)
{
    $clientOrder = ClientHasOrder::where('order_id',$id)->firstOrFail();
    $clientOrder->delete();
    return redirect('/')->with('msg','Order Deleted successfully!');
}

This is the model code:

class clientHasOrder extends Model
{
    use HasFactory;
    
    public $timestamps = false;
    
    protected $fillable = [
        'order_id',
        'product_id',
        'amount',
    ];
}

This is the migration file:

public function up()
{
    Schema::create('client_has_orders', function (Blueprint $table)
    {
        $table->string('order_id')->constrained();
        $table->foreignId('product_id')->constrained();
        $table->string('amount')->default('200');
    });
}

And when i click delete button this is the error im getting:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' 
    
delete from
    `client_has_orders`
where
    `id` is null

showing this line in red: $clientOrder->delete();

When i change the name of column from order_id to id the code works but i dont want to call it id

CodePudding user response:

try it without firstorfail() because you table dose not have an ID.

    public function destroy($id)
    {
        $clientOrder = clientHasOrder::where('order_id', $id)->delete();
        return redirect('/')->with('msg', 'Order Deleted successfully!');
    }

CodePudding user response:

client_has_orders table does not have a column called id. The code is looking for an id column to delete the row, but it does not exist in the table. To fix the issue, you should change id to order_id in the where clause

$clientOrder = ClientHasOrder::where('order_id',$id)->firstOrFail();

make sure that the foreign key order_id in the client_has_orders table references the primary key in the orders table

  • Related