laravel 5将日期和时间插入数据库

时间:2015-10-03 15:23:20

标签: php date datetime laravel

我想插入当前日期或日期和时间以及表单输入...我有这段代码,但我不确定如何包含当前日期,

public function create(Patient $patient, Request $request)
    {
        // $post = $request->all();

        $data = array(
              'pName' => $request['fname'],
              'pAddress' => $request['address'],
              'pBday' => $request['bday'],
              'pPhone' => $request['phone'],
              'pEcon' => $request['econ'],
              'pDreg' => dateTime('created_at')

          );

        $patient->insert($data);

        return redirect('patient');
    }

这是在PatientController.php中..请仅使用laravel 5或5.1中的代码

2 个答案:

答案 0 :(得分:4)

Laravel将在通过迁移生成新数据库表时自动创建两个timestamps()

Schema::create('tasks', function(Blueprint $table)
 {
   ...
   $table->timestamps();
 });

编辑:如果您想管理时间戳,可以在模型中执行:

class YourModel extends Eloquent
      ....

      public static function boot()
      {

           public $timestamps = false;

           parent::boot();

           static::creating(function($model) {
              $dt = new DateTime;
              $model->created_at = $dt->format('m-d-y H:i:s');
              return true;
           });

          static::updating(function($model) {
             $dt = new DateTime;
             $model->updated_at = $dt->format('m-d-y H:i:s');
             return true;
          });
      }

参考:http://laravelsnippets.com/snippets/managing-timestamps

编辑2:

备份参考:https://web.archive.org/web/20151104131317/http://laravelsnippets.com:80/snippets/managing-timestamps

答案 1 :(得分:0)

检查 laravel 5.1 docs 上的可用列类型。 要添加您的列,请执行以下操作:

$table->timestamp('pDreg'); // TIMESTAMP equivalent for the database.  

$table->dateTime('pDreg'); // DATETIME equivalent for the database.

然后在您的 date() 上调用 $date 函数。

$data = [
             'pName' => $request['fname'],
             'pAddress' => $request['address'],
             'pBday' => $request['bday'],
             'pPhone' => $request['phone'],
             'pEcon' => $request['econ'],
             'pDreg' => date('Y-m-d h:i:s')
        ]);