保存模型的laravel从验证中返回json

时间:2016-09-17 23:41:25

标签: ajax laravel laravel-5

您好我在模型中输出有关保存方法的json信息时遇到问题。我收到以下错误 - Response.php第397行中的UnexpectedValueException: Response内容必须是实现__toString()的字符串或对象," boolean"给出。 我在保存时对模型进行验证,在模型的验证方法中我需要输出json,但我得到的是boolean而不是json对象

使用Javascript:

submit: function(e) {

    e.preventDefault();

    var contact = this.model.save({
        firstname: this.firstname.val(),
        lastname: this.lastname.val(),
        company: this.company.val(),
        email_address: this.email_address.val(),
        description: this.description.val(),
    }, {success:function(response){ console.log(response)}, wait: true});       

联系型号:

class Contact extends Model
{
    protected $table = "contacts";

    protected $fillable = ['firstname', 'lastname', 'company', 'email_address', 'description'];

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

        static::creating(function($model) {

            return $model->validate('POST');
        });

        static::updating(function($model) {
            return $model->validate('PUT');
        });

        static::saving(function($model) {            
            return $model->validate('PUT');
        });
    }


    public function rules($method)
    {


        switch($method)
        {
            case 'GET':
            case 'DELETE':
            {
                return [];
            }
            case 'POST':
            {
                return [
                    'firstname' => 'required',
                    'lastname'  => 'required',
                    'email_address' => 'required|email|unique:contacts,email_address',
                    'description' => 'requried'                
                ];
            }
            case 'PUT':
            case 'PATCH':
            {
                return [
                    'firstname' => 'required',
                    'lastname'  => 'required',
                    'email_address' => 'required|email|unique:contacts,email_address,'.$this->id,
                    'description'   => 'required',
                ];
            }
            default: break;
        }

        return [];
    }

    public function messages() {
        return [
            'firstname.required' => 'Please enter your first name.',
            'lastname.required' => 'Please enter your first name.',
            'email_address.required' => 'Please enter a email address.',
            'email_address.email' => 'Please enter a valid email address',
            'email_address.unique' => 'The email is not unique.',
            'description' => 'Please enter a description.'
        ];
    }


    public function validate($method)
    {        
        $data = $this->attributes;

        // if( $data['slug'] === '') {
        //     // if the slug is blank, create one from title data
        //     $data['slug'] = str_slug( $data['title'], '-' );
        // }

        // make a new validator object
        $v = Validator::make($data, $this->rules($method), $this->messages());


        // check for failure
        if ($v->fails())
        {            
            // set errors and return false
            // json here not return response it's always boolean true or false
            return new JsonResponse(array('error' => true, 'errors' => $v->messages()));
        }

        // validation pass
        return true; //new JsonResponse(array('errors'=>false));

    }

    public function errors() {
        return $this->errors;
    }

    public function user() {
        return $this->hasOne('App\User', 'email', 'email_address');
    }
}

保存模型:

    public function update(Request $request, $id) {

    $contact = Contact::find($id)->with('user')->first();
    $contact->firstname = $request->get('firstname');
    $contact->lastname = $request->get('lastname');
    $contact->email_address = $request->get('email_address');
    $contact->company = $request->get('company');
    $contact->description = $request->get('description');       

    return $contact->save(); //return formatted json
}

2 个答案:

答案 0 :(得分:2)

根据您的验证实施,您应该更改以下部分(在Contact中):

// check for failure
if ($v->fails())
{            
    // set errors and return false
    // json here not return response it's always boolean true or false
    return new JsonResponse(array('error' => true, 'errors' => $v->messages()));
}

对于这样的事情:

if ($v->fails()) {            
    $this->errors = $v->errors();
    return false;
}

然后,从Controller开始尝试这样的事情:

// If validation failed

if(!$contact->save()) {
    return response()->json([
        'error' => true,
        'errors' => $contact->errors()
    ]);
}

// Contact created if reached here...
return response()->json(['error' => false, 'contact' => $contact]);

另外,请检查Ajax-Request-ValidationForm-Request-Validation(更简单和可管理)。

注意:请勿尝试从模型中返回任何类型的HTTP Response。返回HTTP response是应用程序逻辑的一部分,模型不应该关注这些。

答案 1 :(得分:0)

因为save()确实返回布尔值所以你要检查它是否正常。

1)更改您的Contact模型,将错误放入模型的错误参数:

/* if($v->fails())  remove/comment this line
  ...
} */
$this->errors = $v->errors();
return !$v->fails();

2)在您的控制器中输入以下代码:

public function update(Request $request, $id) {

    $contact = Contact::find($id)->with('user')->first();
    if(!$contact) {
      return response('Contact not found', 404);
    }

    $contact->firstname = $request->get('firstname');
    $contact->lastname = $request->get('lastname');
    $contact->email_address = $request->get('email_address');
    $contact->company = $request->get('company');
    $contact->description = $request->get('description');       

    return $contact->save()? 
             $contact->toJson() :  // returns 200 OK status with contact (json)
             response($contact->errors, 400); // returns proper 400 Bad Request header with errors (json) in it
}

P.S。很高兴回答具有http状态的请求者,业界已经让所有人都能让开发人员的生活变得轻松,所以如果它不是2xx,则3xx状态如此=>来自客户端应用程序的请求的响应将被视为error(处理程序success: function(response)将不会在此处发现错误)