In Laravel 11, if you want to remove the created_at
and updated_at
columns from a migration, you can do it in several ways depending on your use case. Here’s how:
Removing created_at and updated_at date columns in Laravel 11
1. Removing Columns in an Existing Migration
If you already have a table and want to remove the created_at
and updated_at
columns, create a new migration:
php artisan make:migration remove_created_at_and_updated_at_from_table_name --table=table_name
Then, in the generated migration file, use the dropColumn
method:
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class RemoveCreatedAtAndUpdatedAtFromTableName extends Migration { public function up() { Schema::table('table_name', function (Blueprint $table) { $table->dropColumn(['created_at', 'updated_at']); }); } public function down() { Schema::table('table_name', function (Blueprint $table) { $table->timestamps(); // Esto recreará las columnas si necesitas revertir la migración }); } }
2. Preventing created_at
and updated_at
from Being Created in a New Migration
If you’re creating a new table and don’t want created_at
and updated_at
columns to be added, simply do not call the timestamps()
method in your migration:
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTableNameTable extends Migration { public function up() { Schema::create('table_name', function (Blueprint $table) { $table->id(); $table->string('name'); // Otras columnas... // No llames a $table->timestamps(); }); } public function down() { Schema::dropIfExists('table_name'); } }
3. Disabling created_at
and updated_at
in a Model
If you don’t want Eloquent to automatically handle these columns in a model, disable this functionality in the model class:
namespace App\Models; use Illuminate\Database\Eloquent\Model; class YourModel extends Model { public $timestamps = false; }
Con esta configuración, Eloquent no intentará manejar las columnas created_at y updated_at, incluso si existen en la tabla.
4. Removing Columns Directly in the Database
If you prefer to manually remove the columns in the database, you can execute an SQL query:
ALTER TABLE table_name DROP COLUMN created_at; ALTER TABLE table_name DROP COLUMN updated_at;
Summary
-
To remove columns in an existing migration: Create a new migration and use
dropColumn
. -
To prevent them from being created in a new migration: Do not call
$table->timestamps();
. -
To disable them in a model: Set
public $timestamps = false;
in the model. -
To manually remove them from the database: Use an
ALTER TABLE
SQL query.
I hope this helps you manage the created_at
and updated_at
columns in Laravel 11! 🚀