Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mvnobrega's avatar

Vuejs is converting "null" to string [ SOLVED ]

I need to get information from my database and some of that information is set to "NULL". However, I would like vuejs to take this as an empty string and not a "null" string.

For example, I take it like this:

name: this.user.name,

The name column is set to NULL, however vuejs converts this to a "NULL" string. How can I get the empty string?

I need to take it as empty because the validation of laravel doesn't work, since a string "NULL" is sent

0 likes
9 replies
MohamedTammam's avatar

It doesn't convert null to "null" by default, how are you retrieving that data? and how are you sending it?

1 like
mvnobrega's avatar

@MohamedTammam

Actually, I did a test here and vue takes the empty string. It looks like it's the controller that saves as null. One solution I found was to check if it's null and convert to an empty string, but that doesn't seem like the best practice to me.

Any suggestions to prevent this from happening?

My vuejs component:

methods: {
            userUpdate() {

                const config = {
                    headers: { 'content-type': 'multipart/form-data' }
                }

                let formData = new FormData();
                formData.append('tipo', this.cadastrar.tipo);
                formData.append('cpf_cnpj', this.cadastrar.cpf_cnpj);
                formData.append('nome', this.cadastrar.nome);
                formData.append('username', this.cadastrar.username);
                formData.append('avatar', this.cadastrar.avatar);
                formData.append('whats1', this.cadastrar.whats1);
                formData.append('whats1_v', this.cadastrar.whats1_v);
                formData.append('whats2', this.cadastrar.whats2);
                formData.append('whats2_v', this.cadastrar.whats2_v);
                formData.append('estado', this.cadastrar.estado);
                formData.append('estado_id', this.cadastrar.estado_id);
                formData.append('cidade', this.cadastrar.cidade);
                formData.append('cidade_id', this.cadastrar.cidade_id);
                formData.append('site', this.cadastrar.site);
                formData.append('bio', this.cadastrar.bio);
                formData.append('email', this.cadastrar.email);


                axios.post('/editar-perfil', formData, config, {                 
                   
                })
                .then(response => {
               
                })
                .catch( error => {
                    
    
                });
            },

My controller:

public function updatePerfil(Request $request)
    {

        $validated = $request->validate([
            'tipo' => 'required',
            'nome' => 'required',
            'cpf_cnpj' => 'required',
            'username' => 'required',
            'email' => 'required|string|email|max:255|unique:users,email,'.Auth::user()->id.',id',
            'estado' => 'required',
            'cidade' => 'required',

        ]);


        $file = $request->file('avatar');

        if($file){
            $filename = rand(10000,5000000) . '.'.$file->getClientOriginalExtension();
        }
        

        $year = date("Y");   
        $month = date("m"); 

        $user = User::find($request->user()->id);
        $user->nome = $request->nome;
        $user->perfil_completo = true;
        $user->username = $request->username; dd($request->username);
        if($file){
            $user->avatar = 'media/users/'.$year.'/'.$month.'/'.$filename;
            $file->move('../public/media/users/'.$year.'/'.$month, $filename);
        }
        $user->tipo = $request->tipo;
        $user->cpf_cnpj = $request->cpf_cnpj;
        $user->whats1 = $request->whats1;
        $user->whats1_visivel = $request->whats1_v;
        $user->whats2 = $request->whats2;
        $user->whats2_visivel = $request->whats2_v;
        $user->estado_id = $request->estado_id;
        $user->cidade_id = $request->cidade_id;
        $user->cidade = $request->cidade;
        $user->estado = $request->estado;
        if($request->site == null){
            $user->site = '';    
        }else{
            $user->site = $request->site;
        }
        if($request->bio == null){
            $user->bio = '';
        }else{
            $user->bio = $request->bio;
        }
        
        $user->email = $request->email;
        $user->update();
        //return redirect()->back()->with('status','Student Updated Successfully');
    }

mvnobrega's avatar

@MohamedTammam

Yes, I get the user data by a "props", and some of them are set to "null" at the database level only, but the column itself is empty. When I give a dd($request->name) in the controller I get "Null" inside a string.

MohamedTammam's avatar

@mvnobrega So the problem in the back-end side not in the front-end, how are you storing and retrieving your data?

KenBarlow's avatar

When you initialise the Vue data property this.cadastrar are you setting the default values as null ? or are you setting them as empty strings i.e. ''

For example don't

data() {
   cadastrar: {
       tipo: null,
       cpf_cnpj: null
       etc
   }
}

Do

data() {
   cadastrar: {
       tipo: '',
       cpf_cnpj: ''
       etc
   }
}

Secondly, I noticed you were generating a random filename

$filename = rand(10000,5000000) . '.'.$file->getClientOriginalExtension();

Have a look at Laravels default method of generating a random filename. Saved me some time :)

$file = $request->file('avatar');
 
$name = $file->hashName(); // Generate a unique, random name...
1 like
mvnobrega's avatar

@KenBarlow

As it is a screen to edit the data, I receive the data by a pro and pass it to vuejs, like this:

props: ['user'],
        data(){
            return {
                csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                cidades: '',
                urlnewimage: false,
                formError: false,

                cadastrar: {
                	tipo: this.user.tipo,
                	cpf_cnpj: this.user.cpf_cnpj,
                	nome: this.user.nome,
                    username: this.user.username,
                    avatar: this.user.avatar,
                    whats1: this.user.whats1,
                    whats1_v: this.user.whats1_visivel,
                    whats2: this.user.whats2,
                    whats2_v: this.user.whats2_visivel,
                    estado: this.user.estado,
                    estado_id: this.user.estado_id,
                    cidade: this.user.cidade,
                    cidade_id: this.user.cidade_id,
                    site: this.user.site,
                    bio: this.user.bio,
                    email: this.user.email,
                    loading: false,
                    errors: '' ,
                    updated: false,
                },

            }
        },

I noticed that the data is sent as null when empty, and so far so good. It turns out that when I call $request and the name of the field (example $request->name), the NULL comes as a string, it comes inside of quotes. But until the execution of axios, it is as null, not as string.

It's in the $request that he puts it inside a string

KenBarlow's avatar
Level 3

@mvnobrega I would say the issue lies with Vuejs props, when you're calling this.user.site which may not exist in the database Vue doesn't know what to set this as when passing as a prop, is it a String, is it a number, an object etc

You should set your prop defaults so Vue knows how to handle the properties properly.

Alternatively, you could send the entire object as a JSON.stringify();

let formData = new FormData();
formData.append('avatar', this.avatar);
formData.append('userProps', JSON.stringify(this.cadastrar));

Then in your controller

public function updatePerfil(Request $request) 
{
   $userProps = json_decode($request->userProps, false);
   $validated = Validator::validate($userProps, [
        // Validation rules
   ]);
   $avatar = $request->file('avatar');
   //etc
   //etc
}
1 like
mvnobrega's avatar

Thank you very much. I managed to solve. I just changed it to true, like this: $userProps = json_decode($request->userProps, true);

Now it's working like a charm, thanks a lot for your help (Y) :)

1 like

Please or to participate in this conversation.