首页 > 解决方案 > 如何从laravel route post将数据保存到mysql数据库中

问题描述

我有 web.php 文件

<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
Route::get('/', function () {
    return view('welcome');
});

Route::post('/upload', function (Request $request) {
    $name=$request->file("thing")->getClientOriginalName();
    Storage::disk("google")->putFileAs("",$request->file("thing"),$name);
})->name("upload");
?>

和HTML代码

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Google drive integration in laravel</title>
    <!-- CSS only -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-12">
    
                <br><br><br>
                    <form action="/upload" method="post" enctype="multipart/form-data">
                    @csrf
                    
                    <input type="file" class="form-control" name="thing" id="title">
                    <p id="s"></p>
                    <br>
                    <input type="submit" class="btn btn-sm btn-block btn-danger" value="Upload">
                    </form>
                </div>
            </div>
        </div>
    </body>
</html>

我希望将 $name 变量中接收到的数据Route::post保存在数据库中。就像我有 MySQL 数据库名称“registration”和表“books”,我想将此值保存在“URL”列中,我该怎么做?

标签: phpmysqllaravel

解决方案


首先移动文件,然后保存记录:

Route::post('/upload', function (Request $request, Table $table) {
    $name=$request->file("thing")->getClientOriginalName();
    $request->file->move('dirname', $name);
    $table->column_name = "dirname/{$name}";
    $table->save();
})->name("upload");

推荐阅读