Support the ongoing development of Laravel.io →
posted 7 years ago
Eloquent

i face a problem when i register a user through web service API project, and it was working but suddenly this problem appeared ..

there an error appeared when create the user:

QueryException in Connection.php line 647:
SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value (SQL: insert into `users` (`updated_at`, `created_at`) values (2017-04-26 23:09:20, 2017-04-26 23:09:20))
and what is showed to me that the eloquent create method ignore the fillable attributes.

What i did in my code :

i have a method that do the registration for a user :

public function register()
    {
        $userData  = request()->all();

        $validator = \Validator::make($userData, [
            'name'                  => 'required|alpha_spaces|max:255',
            'email'                 => 'required|email|max:255|unique:users',
            'phone'                 => 'required|phone_number',
            'password'              => 'required|min:6',
            // 'img'                   => 'required'
            // 'address_coordinates'   => 'required'
        ]);

        if ($validator->fails())
        {
            $errors = $validator->failed();
            return response()->json([
                    'message'   => 'validation error',
                    'errors'    => $errors,
                    'code'      => getMsgCode('validationErrors')
            ]);
        }

        $api_token                      = str_random(60);
        while ( count( User::where('api_token',$api_token)->first()) != 0 ) {                    
            $api_token = str_random(60);
        }

        $userData['api_token']            = $api_token;
        $userData['status']               = 1;
        $userData['dashboard_access']     = 0;
        $userData['role']                 = 'member';

        try {
            $user               = User::createUser($userData);
            $user['auth_token'] = $api_token;

        } catch (Exception $e) {
            
            return response()->json([
                    'message'   => 'something went wrong',
                    'code'      => getMsgCode('somethingWrong')
            ]);
        }

        return response()->json([
                'data'      => [
                        'user'        => $user,
                ],
                'message'   => 'success',
                'code'      => getMsgCode()
        ]);
    }

The code above in the try/catch block has the createUser method which it is in the User model :

public static function createUser($userData)
    {
        if( request()->hasFile('img') ) $userData['img'] = User::uploadImage($userData['img']);

        $userData['password']                       = bcrypt($userData['password']);
        $createdUser                                = User::create($userData);

        return $createdUser;
    }

and of course i made the fillable attributes for the User model :

    protected $fillable = [
         'name','email', 'password','img','gender','phone','address_ar','address_en',
'address_coordinates','role','dashboard_access','status','confirmed',
'confirmation_code','api_token','membership_id'
    ];

    protected $hidden = [
        'password', 'remember_token','confirmation_code','api_token',
        'membership_id', 'dashboard_access', 'confirmed',
        'membership_start_date'
    ];

    protected $appends = [
                    'waiting_products',
                    'waiting_services',
                ];

and there is some Accessors that i did recently in the User model and i don't know if they are related to this issue or not :

    protected function getArrayableAttributes()
    {
        if(request()->segment(1) == 'api'){

            foreach ($this->attributes as $key => $value) {
                if ($key == 'deleted_at') continue;

                if ( is_null($value) ) {
                    $this->attributes[$key] = '';
                }
            }
        }

        return $this->getArrayableItems($this->attributes);
    }

    public function getImgAttribute($value)
    {
        if(request()->segment(1) == 'api')
            return $value ? '/images/normal/'.$value : '';

        return $value;
    }

    public function getWaitingProductsAttribute($value)
    {
        return $this->products()->where('status',0)->where('product_type','product')->count();
    }

    public function getWaitingServicesAttribute($value)
    {
        return $this->products()->where('status',0)->where('product_type','service')->count();
    }

i saw some solution of making the strict mode of MYSQL to false in the _ /config/database.php_ file :

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true, // ========> make it to false <========
            'engine' => null,
        ],

but when i did it , there is no value entered the database except the timestamp values !!

  • So anyone can tell me what happened here, where the problem and how can i solve it ?!
  • and what this strict mode in mysql ?

and thanks :)

Last updated 2 years ago.
0

Not sure why you did all of this. You just had to set fillable.

0

@lagbox : i don't know what you mean by all of this ..!!

i already set the fillable and everything was normal and this problem suddenly happened after i made the Accessors ..

all of this to explain the situation and make the problem obvious to you ..

you can read what i did again , and you will see that everything is normal, but i don't know what cause the problem ..

and this is some dd() test :

  • in the createUser method in the User model i dd() the userData variable :
array:9 [
  "email" => "user12@admin.com"
  "password" => "123456"
  "phone" => "0321561235"
  "name" => "ryan"
  "api_token" => "Q3kphRxwQzcdah55yZUS9Ip6Vjt8qi09EkgrlDaRTd8jpYLGwOpqhANcW5Ce"
  "status" => 1
  "dashboard_access" => 0
  "role" => "member"
]
  • and i dd() the fillable attributes of a new instance of the User model :
array:16 [
  0 => "name"
  1 => "email"
  2 => "password"
  3 => "img"
  4 => "gender"
  5 => "phone"
  6 => "address_ar"
  7 => "address_en"
  8 => "address_coordinates"
  9 => "role"
  10 => "dashboard_access"
  11 => "status"
  12 => "confirmed"
  13 => "confirmation_code"
  14 => "api_token"
  15 => "membership_id"
]
0

@lagbox :

in my User model i made a construct to make dynamically hidden attributes :

and when i comment this construct, it worked again .. but idk why this cause this problem :

public function __construct()
    {
        // to hide unused properties in the returned josn api.
        if(request()->segment(1) == 'api'){
            $this->addHidden(['membership_allowed_days']);
        }
        
    }
0

@lagbox : it solved now as i should call the parent construct in User construct to not override the existing mass assignment attributes :)

like this :

    public function __construct($attributes = [])
    {
        // To not override the existing mass assignment attributes
        parent::__construct($attributes);
        
        // to hide unused properties in the returned josn api.
        if(request()->segment(1) == 'api'){
            $this->addHidden(['membership_allowed_days']);
        }
    }
0

Sign in to participate in this thread!

Eventy

Your banner here too?

reyoryan reyoryan Joined 26 Apr 2017

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.