Laravel truncate table | Truncate a table in Laravel | Truncate table Laravel eloquent Code Example | Query Builder - Laravel

In Laravel, you can truncate a table using Eloquent or the Query Builder. Truncating a table deletes all records from the table and resets any auto-incrementing IDs. Here are examples of how to truncate a table using both methods:

  1. Using Eloquent (Model):

    If you have a model associated with the table you want to truncate, you can use Eloquent to truncate it. Here's how:

    php
  • use App\Models\YourModel; // Truncate the table associated with the model YourModel::truncate();

    Replace YourModel with the actual name of your Eloquent model.

  • Using Query Builder:

    You can also use the Query Builder to truncate a table directly. Here's how:

    php
    1. use Illuminate\Support\Facades\DB; // Truncate the table using the Query Builder DB::table('your_table_name')->truncate();

      Replace 'your_table_name' with the actual name of the table you want to truncate.

    Both of these methods will effectively delete all records from the specified table and reset any auto-incrementing IDs. Truncating a table is a more efficient way to delete all records compared to a DELETE query because it doesn't generate as much transaction log.

    Make sure you use the appropriate method based on whether you're working with Eloquent models or directly with the Query Builder in your Laravel application.

    Comments