RoyBarOn
RoyBarOn

Reputation: 987

"Object of class App\User could not be converted to int" error in Laravel

I'm trying to save new user with Ajax request in Laravel and i'm getting the following error,

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

I must add the the user is saved, so i'm not sure from where this error comes.

Here is the 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();
        }

Here is the Ajax request:

$('#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();
                }
            });

        })

Here is the User Model

<?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',
    ];
}

I've tried to convert all the input values to their type - like in the DB but it didn't worked

enter image description here enter image description here

Upvotes: 0

Views: 1809

Answers (2)

zlatan
zlatan

Reputation: 3951

In your condition, you are trying to see if a collection of user is > 0, and because of that, you're getting the error above, since Laravel is trying to parse the collection of user to int datatype, to make it countable. Refactor your condition to this:

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

or another way:

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

Upvotes: 1

Hanan Alhasan
Hanan Alhasan

Reputation: 300

Try to change this in your controller

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

To this

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

Upvotes: 0

Related Questions