Skip to content

Search is only available in production builds. Try building and previewing the site to test it out locally.

Deleting Models

The Laravel-Opensearch integration facilitates model deletion in a manner that’s highly consistent with the Laravel Eloquent ORM, offering a familiar and intuitive interface consistent with Laravel’s Eloquent ORM.

Single Model Deletion

To delete a single model, first, retrieve the model instance using the find method and then call the delete method on the instance. This operation removes the document from the OpenSearch index corresponding to the model.

$product = Product::find('IiLKG38BCOXW3U9a4zcn');
$product->delete();

Find the product with the ID IiLKG38BCOXW3U9a4zcn and delete it.


Mass Deletion

For deleting multiple models based on certain criteria, you can chain the delete method to a query.

Product::whereNull('color')->delete();

Delete all products where the color is null or the color field is missing.


Truncating an Index

The truncate method removes all documents from an index without deleting the index itself. This is useful for quickly clearing all data while preserving the index settings and mappings.

Product::truncate();

truncate() only affects documents, not mappings or index settings.

Remove all documents from the products index but keep the index itself.


Destroy by id

_id under the hood of course

Single id

Product::destroy('9iKKHH8BCOXW3U9ag1_4');

Multiple ids

Product::destroy(
'4yKKHH8BCOXW3U9ag1-8',
'_iKKHH8BCOXW3U9ahF8Q'
);

Multiple ids as an array

Product::destroy([
'4yKKHH8BCOXW3U9ag1-8',
'_iKKHH8BCOXW3U9ahF8Q'
]);

Soft Deletes

Soft deletes add a deleted_at timestamp to the document.

These records are excluded from queries by default, but can be included or restored.

  • withTrashed() → includes soft-deleted records.
  • restore() → removes the deleted_at timestamp.
  • forceDelete() → permanently deletes the documents.

To use soft deletes, include the SoftDeletes trait in your model:

use PDPhilip\OpenSearch\Eloquent\Model;
use PDPhilip\OpenSearch\Eloquent\SoftDeletes;
class Product extends Model
{
use SoftDeletes;
}

With soft deletes enabled, you can include deleted models in your query results using the withTrashed() method:

Product::withTrashed()->where('color', 'red')->get();

Retrieve all products with the color red, including any soft-deleted products.

With soft deletes enabled, you can restore soft-deleted collections using the restore() query:

Product::withTrashed()->where('color', 'red')->restore();

Find all products with the color red and restore any that may have been soft-deleted.

To permanently remove a soft-deleted collection, you can use the forceDelete method:

Product::withTrashed()->where('discontinued_at', '<', '2020-01-01')->forceDelete();