从服务器端使用 Laravel/Lumen 插入数据

Insert Data with Laravel/Lumen from server side

我有一个 post 请求将产品信息添加到数据库,如 ID (UUID)、图像、名称、价格等。

目前我正在使用:

public function store(Request $request) {

    $uuid = Uuid::generate();

    if ($request->hasFile('image')) {
        $image = $request->file('image');
        $name = time().'.'.$image->getClientOriginalExtension();
        $destinationPath = storage_path('/app/images');
        $image->move($destinationPath, $name);


        $product = Product::create($request->all());

        return response()->json(['data'=>"product with id {$product->id} is created"]);
    } 

两个字段 uuid 和图像 URL 都是由 API 生成的,而不是从用户提供的信息中生成的,所以我如何保存所有信息(服务器生成的字段和由post请求)到数据库?

您可以使用array_merge()函数。

Product::create(array_merge($request->all(), [
    'uuid' => $uuid, 
    'image_url' => $imageUrl,
    'name' => $name,
    'price' => $price,
]));

当有 csrf 令牌或其他您不想保存的字段时,请使用 $request->except('_token', etc.) 而不是 $request->all()。确保模型上的所有字段都设置为可填写。