Laravel delete query | Laravel Delete Query Builder | Laravel - Delete Records | Delete record using 'WHERE' - Laracasts

In Laravel, you can delete records from a database table using the Query Builder. The delete method allows you to specify conditions to determine which records should be deleted. Here's how to use it:

php
use Illuminate\Support\Facades\DB; // Delete records based on a WHERE condition DB::table('your_table_name') ->where('column_name', '=', 'value_to_match') ->delete();

Replace the following placeholders with your actual data:

  • 'your_table_name': The name of the database table from which you want to delete records.
  • 'column_name': The name of the column on which you want to apply the condition.
  • 'value_to_match': The value to match in the specified column. Records matching this value will be deleted.

You can also use other comparison operators in the where clause, such as <, <=, >, >=, and <> (not equal), depending on your specific needs.

Here's an example of deleting records from a users table where the status column is equal to 'inactive':

php
use Illuminate\Support\Facades\DB; DB::table('users') ->where('status', '=', 'inactive') ->delete();

This code will delete all records in the users table where the status column is equal to 'inactive'.

You can chain multiple where conditions to delete records based on more complex criteria. For example:

php
use Illuminate\Support\Facades\DB; DB::table('your_table_name') ->where('column1', '=', 'value1') ->orWhere('column2', '>', 100) ->delete();

In this example, records will be deleted from your_table_name where either column1 is equal to 'value1' or column2 is greater than 100.

Make sure to handle database deletions with caution, especially if you're working with production data, as deleted records cannot be easily recovered.

Comments