0

I am using laravel and I want to insert an array to a column but it gives me this error I do not why

here is my query

        DB::table('cart_product')->insert([
          ['product_id' => $request->product_id,'quantity' => $request->quantity, 'cart_id' => \Auth::user()->cart()->get()->first()->id, 'color_id' => $request->color, 'total_price' => $productPrice, 'specification' => $request->specification]
          , ]);

and here is model

class CartProduct extends Model
{
  use SoftDeletes;
  protected $guarded = ['id'];
  protected $dates = ['deleted_at'];
  protected $table = 'cart_product';
  protected $casts = ['specification' => 'array'];
  }
}

and error is for this

$request->specification

here is a dd of this

array:4 [▼
  0 => "4"
  1 => "7"
  2 => "8"
  3 => "9"
]

gives me this error

Array to string conversion

4
  • I did it the last part of my question Commented Feb 10, 2020 at 9:01
  • can you show the table structure of this model? Commented Feb 10, 2020 at 9:03
  • is the specification json type? Commented Feb 10, 2020 at 9:03
  • If this is an array than you can save this field as json in your database Commented Feb 10, 2020 at 9:06

3 Answers 3

3

Casts only work when you use Eloquent Models to execute the queries. When you use the Query Builder directly, your casts are not executed, so you are trying to bind an array to a MySQL query.

Either manually json_encode the value:

DB::table('cart_product')->insert([
    ['specification' => \json_encode($request->specification)]
]);

Or use the eloquent model:

CartProduct::create([
    'specification' => $request->specification,
]);
Sign up to request clarification or add additional context in comments.

Comments

0

Convert Your Array to string

DB::table('cart_product')->insert([[
 'product_id' => $request->product_id,
 'quantity' => $request->quantity,
 'cart_id' => \Auth::user()->cart()->get()->first()->id,
 'color_id' => $request->color, 
 'total_price' => $productPrice, 
 'specification' => '[4, 7, 8, 9]'
]]);

Comments

0

If you want to use DB then you have to user json_encode to save array in your database

DB::table('cart_product')->insert([
          [
          'product_id' => $request->product_id, 
          'quantity' => $request->quantity,
          'cart_id' => \Auth::user()->cart()->get()->first()->id, 
          'color_id' => $request->color,
          'total_price' => $productPrice,
          'specification' => json_encode($request->specification) // add json_enocde here
          ]
          , ]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.