【问题标题】:Manipulating form data before inserting to database在插入数据库之前操作表单数据
【发布时间】:2017-06-05 16:09:03
【问题描述】:

我正在开发一个 API,我正在从移动应用程序获取表单数据以将其存储在数据库表中 workers 我想在将其存储到数据库之前修改列 registration_id 数据

在我的控制器中我像这样存储

public function store()
{
    Driver::create(input::all());

    return $this->respondCreated('Driver created successfully');
}

在我的模型中,我正在尝试将 registration_id 值更改为某个值

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Driver extends Model
{
   use SoftDeletes;

   protected $fillable = [
                           'agent_id',
                           'registration_center',
                           'sponsor_name',
                           'event_name',
                           'registration_id',
                          ];

   protected $dates = ['deleted_at'];

    public function modifyRegistrationId($registration_id)
    {   
        $this->attributes['registration_id'] = 'test';
    }   
}

但它无法正常工作,原始表单值正在插入到数据库中 我如何将registration_id 更改为其他值

期待获得急需的帮助

谢谢

【问题讨论】:

  • 存储到数据库之前是否调用了 modifyRegistrationId() 函数?

标签: php laravel api laravel-5.3


【解决方案1】:

如果您总是覆盖该值,define a mutator:

public function setRegistrationIdAttribute($value)
{
    $this->attributes['registration_id'] = 'test';
}

如果您只想执行一次,请覆盖该值:

public function store(Request $request)
{
    $request->registration_id = 'test';
    Driver::create($request->all());

    return $this->respondCreated('Driver created successfully');
}

【讨论】:

  • @Alexey Mezenin 它有效!非常感谢我真的很感激,你能告诉我如何检查最后插入的registration_id,增加它并将当前日期附加到它并插入到数据库中谢谢
  • @MrRobot 你可以使用相同的$request-&gt;date = Carbon::now() 设置日期,但最好使用Laravel 的created_at。要获取插入行的 ID,请执行此操作 $id = Driver::create($request-&gt;all())-&gt;id; 而不是 Driver::create($request-&gt;all());
【解决方案2】:

您可以使用事件在保存之前更改任何数据。看看Laravel docs。这里我们使用boot()定义回调行为:

class Driver extends Model 
{

    public static function boot()
    {
        parent::boot();

        self::creating(function($model){
            //before create, do this...
            $lastRegistrationId = Driver::orderBy('id', 'desc')->first()->registration_id;
            $this->registration_id = $lastRegistrationId.date('Y-m-d');
        });
    }
    ...
}

您可以使用的功能有:创建、创建、更新、更新、保存、保存、删除、删除、恢复、恢复

【讨论】:

  • 非常感谢您的宝贵时间,您能告诉我如何检查最后一个registration_id,将当前日期附加到它并插入数据库,谢谢
  • 不确定你想要什么。 registration_id 将是一个 INT 类型。如果您附加当前日期,将更改为字符串/varchar。如果您尝试存储将引发错误。你到底想做什么?
  • registration_id 不是 INT 它是一个字符串,我只想将当前日期附加到它
  • 好的,已编辑。您可以根据需要格式化日期格式。在我看来,在处理 varchar 字段时不应该使用“id”。它不遵循 Laravel 的惯例。
猜你喜欢
  • 2015-10-25
  • 1970-01-01
  • 1970-01-01
  • 2018-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多