Laravel 5.2在控制器之前进行表单验证后修改请求

时间:2016-10-14 07:35:49

标签: php laravel validation

我正在使用laravel 5.2并且我使用laravel供应商提供的表单请求来清理我的代码,所以我的控制器上没有很多代码:

    private void dgv_RowValidating( object sender, DataGridViewCellCancelEventArgs e )
    {
        try
        {
            if (!dgv.IsCurrentRowDirty)
                return;

            string query = GetInsertOrUpdateSql(e);
            if (_conn.State != ConnectionState.Open)
                _conn.Open();

            var cmd = new SqlCommand( query, _conn );
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            MessageBox.Show( ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning );
        }
    }

    public string GetInsertOrUpdateSql( DataGridViewCellCancelEventArgs e )
    {
        DataGridViewRow row = dgv.Rows[e.RowIndex];
        int id = 0;
        int.TryParse( row.Cells["Id"].Value.ToString(), out id );

        DateTime dob;
        DateTime.TryParse( row.Cells["Dob"].Value.ToString(), out dob );

        string email = row.Cells["Email"].Value.ToString();
        string phone = row.Cells["Phone"].Value.ToString();
        string fio = row.Cells["Fio"].Value.ToString();

        if (id == 0)
            return string.Format( "insert into {0}  Values ('{1}','{2}','{3}','{4}')", "dbo.People", fio, dob.ToString( "dd-MM-yyyy" ), email, phone );
        else
            return string.Format( "update {0} set Fio='{1}', Dob='{2}', Email='{3}', Phone='{4}' WHERE Id={5}", "dbo.People", fio, dob.ToString( "dd-MM-yyyy" ), email, phone, id );
    }
    private void dgv_UserDeletingRow( object sender, DataGridViewRowCancelEventArgs e )
    {
        try
        {
            int id = 0;
            int.TryParse( e.Row.Cells["Id"].Value.ToString(), out id );
            string query = string.Format( "DELETE FROM {0} WHERE Id = {1}", "dbo.People", id );
            var cmd = new SqlCommand( query, _conn );
            if (_conn.State != ConnectionState.Open)
                _conn.Open();
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            MessageBox.Show( ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning );
        }
    }

这是关于我的申请表的示例代码:

public function store( CouponRequest $request )
{
    DB::beginTransaction();
    try {
        $coupon = Coupon::create( $request->all() );

        DB::commit();
        return redirect()->route('admin.coupons.index');
    } catch (\Exception $e) {
        DB::rollback();
        return redirect()->back()->withInput();
    }

我应该在哪里放置此命令? :

public function rules()
{
    switch ( strtolower( $this->method ) ) {
        case 'post':
        {
            return [
                'code' => 'required|unique:coupons,code',
                'name' => 'required',
                'start_year' => 'required',
                'start_month' => 'required',
                'start_day' => 'required',
                'start_time' => 'required',
                'finish_year' => 'required',
                'finish_month' => 'required',
                'finish_day' => 'required',
                'finish_time' => 'required',
                'using_time' => 'required',
                'type' => 'required',
                'free_shipment' => 'required',
                'target' => 'required',
                'target_user' => 'required'
            ];
        }
        case 'put':
        {
            return [
                'code' => 'required',
                'name' => 'required',
                'start_year' => 'required',
                'start_month' => 'required',
                'start_day' => 'required',
                'start_time' => 'required',
                'finish_year' => 'required',
                'finish_month' => 'required',
                'finish_day' => 'required',
                'finish_time' => 'required',
                'using_time' => 'required',
                'type' => 'required',
                'free_shipment' => 'required',
                'target' => 'required',
                'target_user' => 'required'
            ];
        }
        default:
        {
            return [];
        }
    }
}

如果我在验证之前放置此代码,当某些字段未被用户填写时,我可能会出错。

所以我想要的是在验证成功后放置此代码,但我不想将它放在我的控制器上。

是否有可以在验证成功后调用的FormRequest函数来修改我的请求?

我觉得在控制器上有很多代码时效果不好,所以我想最小化我的控制器代码。

1 个答案:

答案 0 :(得分:0)

我将尝试使用FormRequest。如果这里的意图是 验证 分配 start_date和finish_date,这可能是在Laravel中这样做的合理方式:

public function rules()
{
    switch ( strtolower( $this->method ) ) {
        case 'post':
        {
            return [
                'code' => 'required|unique:coupons,code',
                'name' => 'required',
                'start_year' => 'required',
                'start_month' => 'required',
                'start_day' => 'required',
                'start_time' => 'required',
                'finish_year' => 'required',
                'finish_month' => 'required',
                'finish_day' => 'required',
                'finish_time' => 'required',
                'using_time' => 'required',
                'type' => 'required',
                'free_shipment' => 'required',
                'target' => 'required',
                'target_user' => 'required'
            ];
        }
        case 'put':
        {
            return [
                'code' => 'required',
                'name' => 'required',
                'start_year' => 'required',
                'start_month' => 'required',
                'start_day' => 'required',
                'start_time' => 'required',
                'finish_year' => 'required',
                'finish_month' => 'required',
                'finish_day' => 'required',
                'finish_time' => 'required',
                'using_time' => 'required',
                'type' => 'required',
                'free_shipment' => 'required',
                'target' => 'required',
                'target_user' => 'required'
            ];
        }
        default:
        {
            return [];
        }
    }
}

/**
 * @inheritDoc
 *
 * This method overrides Laravel's defeault FormRequest
 * to create validator with `after()` hook
 */
protected function validator($validator)
{
    $validator
        ->make(
            $this->validationData(), $this->rules(), $this->messages(), $this->attributes()
        )
        ->after(function($validator) {

            if ($date = $this->getCarbonInstanceFromPrefix('start')) {
                $request->start_date = $date;
            } else {
                $validator->errors()
                    ->add('start_year', 'Invalid starting date and time');
            }

            if ($date = $this->getCarbonInstanceFromPrefix('finish')) {
                $request->finish_year = $date;
            } else {
                $validator->errors()
                    ->add('finish_year', 'Invalid finish date and time');
            }

        });
}

/**
 * Retrieve carbon instance from current request, using prefix
 *
 * @param  string $prefix
 *
 * @return Carbon|null
 */
protected function getCarbonInstanceFromPrefix($prefix = '')
{
    try {
        $date = Carbon::create( 
            $request->get($prefix . '_year'), 
            $request->get($prefix . '_month'), 
            $request->get($prefix . '_day') 
        );
        $date->setTimeFromTimeString( $request->get($prefix . '_time') );
        return $date;
    } catch (\Exception $e) {
        return null;
    }
}

快速解释

FormRequest基本上从Illuminate\Foundation\Http\FormRequest扩展,并且可以覆盖创建Validator实例的方法。通过创建自定义验证程序,您可以附加after()事件以验证每个日期输入,还可以一次性为请求分配其他参数。