Home > database >  How to insert/save an array data into database as one value
How to insert/save an array data into database as one value

Time:09-09

I used checkbox to select multiple value and I was able to store it into one variable as string and display it without a problem. Unfortunately when I'm trying to save it into my database it gives me an error "Array to string conversion". What should I do to save/insert it into the database as one value. The variable that holds the array value is products.

public function mydatabase(Request $request)
{
    $data = new mydatabase;
    $data->name=$request->name;
    $data->email=$request->email;
    $data->phone=$request->phone;
    $data->address=$request->address;
    $data->date=$request->date;
    $data->time=$request->time;
    $data->products=$request->products;

    $data->save();
    return  redirect()->back();

}

CodePudding user response:

you can use : serialize()/unserialize(), or json_encode()/json_decode() or impode()/explode(). When using Laravel use : toJson().

CodePudding user response:

For products column, you can define a mutator or setter in related model of table

public function setProductsAttribute($value)
{ $this->attributes[`products`]= json_encode($value) ;}

To get data as array

public function getProductsAttribute()
{ return json_decode($this->products,true);}
  • Related