Search code examples
jqueryajaxlaraveltags

Store tag input values in a single column into database using Laravel8


I Have the following form with a tag input.

<form id="filialeform" action="filiales" enctype="multipart/form-data">
  {{ csrf_field() }}
  <input type="hidden" id="id_hidden" name="id" />
  <div class="form-group">
    <label>Filiale</label>
    <input type="text" class="form-control" name="filiale" id="filiale" placeholder="Filiale">
  </div>
  <div class="form-group">
    <label>Adm_Email</label>
    <input data-role="tagsinput" type="text" name="adm_email" id="adm_email">
  </div>
  <div class="modal-footer">

    <input type="hidden" name="action" id="action" />
    <input type="hidden" name="hidden_id" id="hidden_id" />
    <input type="submit" name="action_button" id="action_button" class="btn btn-warning" value="Enregistrer" />
    <span id="form_result"></span>
  </div>
</form>

And I have the following database table :

 public function up()
    {
        Schema::create('filiales', function (Blueprint $table) {
                
            $table->increments('id_filiale');
            $table->string('filiale',80);
            $table->string('adm_email',500);
            $table->integer('actif');
            $table->timestamps();
        });
    }

I'mtrying to store data into database,so that the values entered in the input tag are stored in the adm_email column of the table separated with gamma.

So I'm trying the following code :

 public function store(Request $request)
    {

        $input = $request->all();
        $tags = explode(",", $request->adm_email);
        $form_data = array(
             'filiale'     =>  $request->filiale,
             'adm_email'    =>   $tags
                        
                    );

         Filiale::create($form_data);

     return response()->json(['success' => 'Data Added successfully.']);
    }

But I'm getting the following error :

message: "Array to string conversion"

I don't know how can I realize that . If you have any idea please help.


Solution

  • Go to Model/Filiale.php and add this:

    protected $casts = [
        'adm_email' => 'array',
    ];
    

    Model make the conversion to and from array automatically.