You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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.

1. 如何在Laravel API中实现向数据表插入数据

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 YourModelName
    

    Note: Laravel uses plural table names by default (e.g., Post model maps to posts table). If your table has a non-standard name, define it in the model with protected $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 a store method to handle the insertion. You can use either the create() 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
    Open routes/api.php and define a POST route for your insertion endpoint:

    use App\Http\Controllers\YourModelController;
    
    Route::post('/your-endpoint', [YourModelController::class, 'store']);
    
2. 解决"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list'"报错

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 $timestamps property set to false:

    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_time instead of created_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 12:52:46