How to include a string in the database from an input array with Laravel?

0

I need to include a string-shaped data in the table in my database that I will get through the input, which in turn is an array. Follow the form for you to see how it is.

<div class="form-inline col-md-12">
                    <div class="form-group col-md-4">
                        <label for="create-contest-theme#1" class="control-label">1º Tema: </label>
                        <div class="input-group">
                            <input type="text" name="theme[]" id="create-contest-theme#1" class="form-control">
                        </div>
                    </div>

                    <div class="form-group col-md-4">
                        <label for="create-contest-theme#2" class="control-label">2º Tema: </label>
                        <div class="input-group">
                            <input type="text" name="theme[]" id="create-contest-theme#2" class="form-control">
                        </div>
                    </div>

                    <div class="form-group col-md-4">
                        <label for="create-contest-theme#3" class="control-label">3º Tema: </label>
                        <div class="input-group">
                            <input type="text" name="theme[]" id="create-contest-theme#3" class="form-control">
                        </div>
                    </div>
                </div>

The action of this form points to the function create of my controller:

public function create(CreateRequest $request){
    $inputs = $request->except('_token');

    $contest = Contest::create($inputs);

    return $contest;
}

The Constest model

  class Contest extends Model
    {
        protected $table = 'contests';
}

And my big question is: How to treat this input theme so that it is a string when it is stored?

    
asked by anonymous 22.04.2017 / 05:30

2 answers

0

Laravel 5.4 is missing, and you want to save each item in the array as a record in the database.

You need the $ fillable property in the model to do a Mass Assigment .

When you fill an Eloquent template with an array using the functions create , fill or update , for security reasons you need to tell which fields will be accepted.

Example

class Contest extends Model
{
    protected $table = 'contests';
    protected $fillable = ['campo_1', 'campo_2', 'campo_3'];
}
    
23.04.2017 / 02:20
0

I found what I wanted, the solution was very simple, I did not understand how things worked very well in laravel, it was a matter of reading the documentation and everything became clearer.

Solution:

public function create(CreateRequest $request){
    $inputs = $request->except('_token');
    $inputs['themes'] = implode(",", inputs['themes']);

    $contest = Contest::create($inputs);

    return $contest;
}

What I was doing before was trying to change the value of request when I should change the value of the returned array $inputs

    
24.04.2017 / 06:25