Automatically Populating Timestamps in Laravel
Storing static dates like '2017-04-27 10:29:59' inside your application logic is a common beginner mistake that quickly becomes unmanageable. When you manually construct an array with fixed timestamps and pass it to DB::table()->insert(), you are hard-coding the moment of creation into your codebase. This approach fails as soon as time zones shift, developers change servers, or you need to audit data created in the future versus the present.
To solve this, Laravel provides a robust mechanism to handle timestamps automatically without you needing to worry about the specific date string format or the current server time. The standard practice involves defining the created_at and updated_at columns in your database migrations with the appropriate types, such as timestamp or datetime, and then leveraging Eloquent's built-in mutators.
Defining the Columns in Migrations
Before writing any logic, ensure your database schema is ready. You should define these columns in your migration file using the timestamps() helper method. This single call creates both columns with default behaviors that are crucial for audit trails.
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('address');
// This creates created_at and updated_at as TIMESTAMP columns
$table->timestamps();
});
By using timestamps(), you are telling Laravel to expect these fields. If you attempt to insert data without them, the database will reject it unless you explicitly provide values. However, once defined, you do not need to manually assign them in your controller code.
Using Eloquent Models Automatically
The most efficient way to handle this is by defining a Model for your students table. When you define a model with a $fillable array that includes only the non-timestamp fields, Laravel automatically manages the rest.
Here is how your controller method should look. Notice that we completely remove the hardcoded '2017-04-27 10:29:59' strings from the data array.
use Illuminate\Http\Request;
use App\Models\Student; // Assuming you have a Student model
public function insert(Request $req)
{
// Only define the attributes that should be mass-assigned
$name = $req->input('name');
$address = $req->input('address');
// Create a new instance or use create() directly
$student = Student::create([
'name' => $name,
'address' => $address,
]);
return redirect('/');
}
When you call Student::create() with only the name and address, Laravel detects that the model belongs to a table with created_at and updated_at. It automatically fetches the current time from the database server's clock at the exact moment the row is inserted. This ensures data consistency regardless of when or where the code runs.
The Trade-off: Mass Assignment Security
A critical pitfall to avoid is accidentally exposing your timestamps to mass assignment vulnerabilities if you are not careful with your $fillable property. If your $fillable array includes created_at and updated_at, a malicious request could theoretically manipulate these fields. While Laravel protects against this by default for non-mass-assignable traits, it is best practice to keep timestamps out of the fillable list unless you have a specific reason to allow them.
By keeping them out of $fillable, you force the framework to handle them exclusively through its internal logic, ensuring that created_at always reflects the true moment of insertion and cannot be spoofed by an incoming request parameter. This separation of concerns keeps your data integrity intact.
If you ever need to manually set a timestamp, such as updating a record created in the past, you can use the model's methods like $student->created_at = now()->subHours(1); before saving, but for standard inserts, letting Laravel handle it is the safest and most maintainable approach.
