如何在Laravel API中向数据表插入数据?及解决无created_at/updated_at字段时的SQL报错问题
Hey there! Let's break down your two Laravel API questions and walk through solutions step by step.
Here's a straightforward, step-by-step approach to insert data into your database via a Laravel API:
Create a Model (if you haven't already)
First, generate a model that maps to your database table. If you don’t need a migration (since you mentioned you already have a database), just run:php artisan make:model YourModelNameNote: Laravel uses plural table names by default (e.g.,
Postmodel maps topoststable). If your table has a non-standard name, define it in the model withprotected $table = 'your_custom_table_name';.Set Fillable Fields
Laravel protects against mass assignment by default, so you need to specify which fields can be inserted in your model:class YourModelName extends Model { // Replace with your actual table fields protected $fillable = ['field1', 'field2', 'field3']; }Write Insert Logic in a Controller
Create an API controller (or use an existing one) and add astoremethod to handle the insertion. You can use either thecreate()method (for mass assignment) or instantiate the model and save it manually:use App\Models\YourModelName; use Illuminate\Http\Request; class YourModelController extends Controller { public function store(Request $request) { // Optional but highly recommended: Validate incoming data $validatedData = $request->validate([ 'field1' => 'required|string', // Adjust rules to match your field types 'field2' => 'required|integer', 'field3' => 'nullable|email', ]); // Method 1: Mass assignment with create() $record = YourModelName::create($validatedData); // Method 2: Manual assignment and save // $record = new YourModelName(); // $record->field1 = $request->field1; // $record->field2 = $request->field2; // $record->save(); // Return a JSON response (standard for APIs) return response()->json([ 'status' => 'success', 'message' => 'Data inserted successfully', 'data' => $record ], 201); // 201 = Created HTTP status code } }Add an API Route
Openroutes/api.phpand define a POST route for your insertion endpoint:use App\Http\Controllers\YourModelController; Route::post('/your-endpoint', [YourModelController::class, 'store']);
This error happens because Laravel's Eloquent models automatically try to manage created_at and updated_at timestamp fields by default. Since your table doesn't include these, you need to disable this behavior in your model:
Disable Automatic Timestamps
Open your model file and add the$timestampsproperty set tofalse:class YourModelName extends Model { // If your table name is non-standard, add this line too // protected $table = 'your_table_name'; public $timestamps = false; // Your $fillable or other configurations... }Alternative: Use Custom Timestamp Fields (If Needed)
If you do have timestamp fields but with different names (e.g.,created_timeinstead ofcreated_at), you can tell Laravel to use those instead:class YourModelName extends Model { const CREATED_AT = 'created_time'; const UPDATED_AT = 'updated_time'; }But if your table has no timestamp fields at all, the first solution is the way to go.
内容的提问来源于stack exchange,提问作者Mohammed_Alkhatib

