lundi 18 novembre 2019

How to specify a nullable value on create function on modal in Laravel?

In a Model, how are we able to insert a nullable validated field, with the create function? For Eg: The in the RegisterController, This is the Basic validator + the Create function. If I didn't sent the google_id or facebook_id, the create function returns undefined index (obviously) on the fields. But What's the proper way to insert them ?

protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['nullable', 'email', 'unique:users'],
            'google_id' => ['nullable', 'string', 'unique:users'],
            'facebook_id' => ['nullable', 'string', 'unique:users'],
            'twitter_id' => ['nullable', 'string', 'unique:users'],
            'phone' => ['required', 'string', 'max:10', 'min:10', 'unique:users', "regex:/(^[1-9][0-9]*$)/"],
            'country_code' => ['required', 'string', 'max:255', 'exists:'.config('countries.table_name').',calling_code'],
            'password' => ['required', 'string', 'min:8'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'phone' => $data['country_code'].$data['phone'],
            'google_id' => $data['google_id']?$data['google_id']:null,
            'facebook_id' => $data['facebook_id']?$data['facebook_id']:null,
            'twitter_id' => $data['twitter_id']?$data['twitter_id']:null,
            'password' => Hash::make($data['password']),
        ]);
    }

This is a very basic question, and I do know how to ignore them, but I really need to know, what the correct format is.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire