如果请求值为空,Laravel 设置默认值

标签 laravel request migration default-value

我正在尝试为 laravel 迁移设置默认值。我正在使用 SQLite。
当我尝试使用分配了默认值的字段插入记录时,返回错误:SQL 错误或缺少数据库(表客户没有名为 country 的列)
这是迁移脚本:

php
Schema::create('customers', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('contact_person_first_name');
            $table->string('contact_person_name');
            $table->string('contact_person_email_address');
            $table->string('address');
            $table->string('zipCode');
            $table->string('city');
            $table->string('country')->default("BELGIË");
            $table->string('vat_number')->default("BE");
            $table->timestamps();
Controller :
     * Store a newly created resource in storage.
     *
     * @param CreateCustomerRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(CreateCustomerRequest $request)
    {
        Customer::create($request->validated());
        return response()->redirectTo('/customers');
    }
请求:
 /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|string|min:2|max:255',
            'contact_person_first_name' => 'required|string|min:2|max:255',
            'contact_person_name' => 'required|string|min:2|max:255',
            'contact_person_email_address' => 'required|email',
            'address' => 'required|string|min:2|max:255',
            'zipCode' => 'required|string|min:4|max:10',
            'city' => 'required|string|min:2|max:255',
            'country' => 'nullable|string|min:2|max:255',
            'vat_number' => 'nullable|min:12|max:12'
        ];
    }
我要执行的sql脚本:
enter image description here
来自数据库 GUI 的一些屏幕截图
Database headers
enter image description here

最佳答案

您已在数据库层中设置了默认值。但它不可为空。这导致了这里的问题。您的请求国家/地区为空,并且您在创建新行时分配了该空值。要么你必须使用 nullable 来插入空值,要么你必须在创建时设置一个值。
用于数据库

$table->string('country')->nullable()->default("BELGIË");
对于您的情况,这不是一个好的解决方案。所以你可以使用一些东西
Customer::create([
    'name' => $request->name,
    'country' => $request->country ?? 'BELGIË',
    //other attributes
]);

关于如果请求值为空,Laravel 设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64134554/

相关文章:

javascript - jstree 使用 contextmenu 插件和 laravel 创建编辑重命名功能

mysql - 迁移 Rails 基表,表名称包含 *

php - 将配置文件中的数据保存到数据库(Laravel 5.3)

laravel - 在 laravel-passport-social-grant 包上获取 invalid_credentials

python - 为一个名称 urllib2 发送多个值

ajax - FedEx API 跟踪包裹 XML url 是什么?

mysql - Rails 将列更改为 mediumtext

java - ElasticSearch 架构迁移

laravel - 在 Kubernetes 中部署 Laravel

http - Telegram 机器人 API 响应 403 Forbidden