Getting error exception "array to string conversion"

Published 2 months ago by Gabotronix

I'm getting the following error thrown when I try to save an email into a database, what I'm trying to do is the classic subscription system.

This is my full error:

exception: "ErrorException"
​
file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Database\Grammar.php"
​
line: 39
​
message: "Array to string conversion"
​
​​
8: Object { file: "C:\xampp\htdocs\Restaurante1\app\Http\Controllers\SubscriptionController.php", line: 44, function: "save", … }
​​
9: Object { function: "store", class: "App\Http\Controllers\SubscriptionController", type: "->" }

​​```
This is my JQuery code:
```php
$(document).ready(function(){
    
    
    
    $(".startSubscription").click(function(){
        var form = $(this).closest('form');
        $('.form_error_text').hide();
        $('.form_valid_text').hide();
        console.log('button start subscription clicked');
        
        var emailval=$("input[name='email']").val();
        
        
        $.ajaxSetup({
            
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')}
        
        });
        
        $.ajax({
            
            async: true,
            cache: false,
            url: '/subscriptions',
            type: 'POST',
            data: 
            {
                
            'email': emailval
            
            },
            dataType: 'JSON',
            
            success: function (data) { 
                $('.form_valid_container').html('<span class="form_valid_text">✓ '+ data.success +'</span>');
                form.trigger("reset");
                console.log(data.success);
            },
            
            error: function (data){
                var errors = data.responseJSON;
                console.log(errors);
                
                $.each(errors , function(){
                    $('.form_error_container').html('<span class="form_error_text">✘ '+ errors.message +'</span>')
                }); 
            }

        }); 
    });
    

});

And my controller where I save the email to a database:

public function store(StoreSubbedMail $request)
    {
        $subscription = new Subscription();
        $subscription->email = $request->email;
        $subscription->save();
        
        return response()->json([
        
            'success' => 'Te subscribiste correctamente'
        ]);
    }
Best Answer (As Selected By Gabotronix)
Cronix

From your other thread on this that I was helping with yesterday, I told you that you need to prevent the default click button, which you still haven't done. I'm pretty sure that you're (still) sending your regular form in addition to your ajax request, since the button with the class startSubscription your clicking is in a form.

Change this

$(".startSubscription").click(function(e){
    e.preventDefault();

Also when testing ajax, you shouldn't dd() from the controller. That will send a bunch of html/javascript and hard to decipher. Just return the data and it will be displayed as json.

lostdreamer_nl

I think your problem is in this line of javascript:

var emailval = $("input[name='email']").val();

That will return an array of the values of all inputs named 'email' , try this one:

var emailval = $("input[name='email']").first().val();

Also, when you're having problems with request values, start debugging.... For javascript you can use the console (Hit F12, and use console.log() in javascript to output values of variables into that console), and for the backend part, you could simply check with:

n store(StoreSubbedMail $request)
    {
        dd($request->all());

        $subscription = new Subscription();
        $subscription->email = $request->email;
        $subscription->save();
        
        return response()->json([
        
            'success' => 'Te subscribiste correctamente'
        ]);
    }

To see what is in the request exactly.

Gabotronix

Changed it but still getting the same error

lostdreamer_nl

Try the debugging note and show what it outputs:

public function store(StoreSubbedMail $request)
    {
    dd($request->all());
    }
Snapey
Snapey
2 months ago (992,285 XP)

you need to debug things, not just blindly write it to tge database

Gabotronix

I added dd like you did and the request got 200 status, this is also the response I'm getting:

array:1 [
  "email" => "[email protected]"
]
lostdreamer_nl

And you are sure that the line giving the error in SubscriptionController.php line 44 is:

$subscription->save();

What is the output of this?:


public function store(StoreSubbedMail $request)
    {
        $subscription = new Subscription();
        $subscription->email = $request->email;
        dd($subscription->toArray());
        $subscription->save();
        
        return response()->json([
        
            'success' => 'Te subscribiste correctamente'
        ]);
    }
Gabotronix

This is the outpout, same as earlier:

array:1 [
  "email" => "[email protected]"
]
lostdreamer_nl

And this gives the error again? (moved the dd() call 1 line below the save() )


public function store(StoreSubbedMail $request)
    {
        $subscription = new Subscription();
        $subscription->email = $request->email;
        $subscription->save();
        dd($subscription->toArray());
        
        return response()->json([
        
            'success' => 'Te subscribiste correctamente'
        ]);
    }

If so, do you have some event listener for the 'saving' event on Subscription ?

Gabotronix

That gives me the error, so it's safe to assume it's the save ing method which throws the exception, it's really werid.

I don't have any event listener neither

lostdreamer_nl

Really strange, how about this one:


public function store(StoreSubbedMail $request)
    {
        Subscription::saving(function($subscription) {
            dd("saving:", $subscription->toArray());
        });

        $subscription = new Subscription();
        $subscription->email = $request->email;
        $subscription->save();

        dd("saved: ", $subscription->toArray());
        
        return response()->json([
        
            'success' => 'Te subscribiste correctamente'
        ]);
    }

This should attach an event listener to the subscription model and output what it's trying to save so no error I hope...

It should simply output something like

string:7 "saving:"

array:1 [
  "email" => "[email protected]"
]
Cronix
Cronix
2 months ago (726,250 XP)

From your other thread on this that I was helping with yesterday, I told you that you need to prevent the default click button, which you still haven't done. I'm pretty sure that you're (still) sending your regular form in addition to your ajax request, since the button with the class startSubscription your clicking is in a form.

Change this

$(".startSubscription").click(function(e){
    e.preventDefault();

Also when testing ajax, you shouldn't dd() from the controller. That will send a bunch of html/javascript and hard to decipher. Just return the data and it will be displayed as json.

Cronix
Cronix
2 months ago (726,250 XP)

Give your email field an id, and use that id to get the value.

<input type="email" name="email" id="email-field">
var emailval=$("#email-field").val();

Also json properties shouldn't be quoted.

data: 
            {
                
            'email': emailval
            
            },

remove the quotes from 'email'

Please sign in or create an account to participate in this conversation.