Laravel中的“类App \ User的对象无法转换为int”错误

时间:2019-08-25 07:58:03

标签: ajax laravel

我试图在Laravel中使用Ajax请求保存新用户,但出现以下错误

Object of class App\User could not be converted to int

我必须添加保存的用户,所以我不确定该错误来自何处。

这是UserController:

public function save_user(Request $request)
    {
        try {
            if (request()->ajax()) {
                $lastUserId = User::where('user_id', '>', 0)->orderBy('user_id', 'desc')->get('user_id')->first()->toArray();

                $user = new User;
                $data = Input::all();
                $user->user_id = intval($lastUserId['user_id'] + 1);
                $user->user_type = $data['user_type'];
                $user->email = $data['email'];
                $user->password = 'e10adc3949ba59abbe56e057f20f883e';
                $user->first_name = $data['first_name'];
                $user->last_name = $data['last_name'];

                $user->save();
                if ($user > 0) {
                    return response()->json('Success');
                }
                return response()->json(['status' => 200, 'message' => 'save success']);
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
        }

这是Ajax请求:

$('#saveUser').on('click', function (e) {
            e.preventDefault();
            var $inputs = $('#new-user-form :input');

            var values = {};
            $inputs.each(function () {
                if (this.name != '_token' && this.name.length > 0) {
                    values[this.name] = $(this).val();
                }

            });

            $.ajax({
                url: '/api/save_user',
                type: "post",
                data: values,
                dataType: 'JSON',
                success: function (data) {
                    /// location.reload();
                }
            });

        })

这是用户模型

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Detail;
class User extends Authenticatable
{

    public function users(){
        return $this->hasMany('\App\User'); //Product Model Name
    }
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

我试图将所有输入值转换为它们的类型-就像在数据库中一样,但是没有用

enter image description here enter image description here

2 个答案:

答案 0 :(得分:0)

尝试在您的控制器中进行更改

if ($user > 0) {
   return response()->json('Success');
}

对此

if ($user) {
   return response()->json('Success');
}

答案 1 :(得分:0)

在您的情况下,您尝试查看某个collection用户是否为> 0,因此,由于Laravel试图解析{{ 1}}用户使用collection数据类型,以使其可计数。将此条件重构为:

int

或另一种方式:

if (count($user) > 0) {
  return response()->json('Success');
}