Laravel при сохранении модели вернуть JSON из проверки

-1

Привет, У меня проблема с выдачей моей json информации о методе сохранения в модели. Я получаю следующую ошибку: UnexpectedValueException в строке Response.php 397: Содержимое ответа должно быть строкой или объектом, реализующим __toString(), "boolean". Я выполняю проверку на модели при сохранении и в методе проверки правильности модели, которую мне нужно, чтобы поставить json, но я получаю boolean вместо json object

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 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
}
Теги:
laravel-5

2 ответа

2
Лучший ответ

Согласно вашей реализации проверки, вы должны изменить следующую часть (в Contact):

// check for failure
if ($v->fails())
{            
    // set errors and return false
    // json here not return response it 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-Validation и Request-Request-Validation (упростить и усовершенствовать).


Примечание. Не пытайтесь вернуть какой-либо HTTP Response от модели. Возвращение HTTP response является частью вашей логики приложения, и модель не должна заботиться об этом.

0

Поскольку save() возвращает boolean, вы должны проверить, нормально ли это.

1) Измените модель Contact чтобы помещать ошибки в модель ошибок. Param:

/* 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
}

ps приятно ответить на запрос с http-статусом, индустрия сделала все, чтобы сделать жизнь разработчика легкой, поэтому, если это не 2xx, статус 3xx так => ответ для вашего запроса с клиентского приложения будет рассматриваться как error (success: function(response) обработчика success: function(response) не будет здесь ошибочной ошибкой)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню