iori
iori

Reputation: 3506

How to gather value(s) from check-boxes, and sync that value to a pivot table?

I want to grab the value from checkboxes, and sync those value into my pivot table.

I have 3 tables :

Here is what I've tried

View > My check-boxes

    {{ Form::label('export_frequency' , 'Export Frequency', array('class'=> 'required cool-blue'))}} <br>

    @foreach (ExportFrequency::all() as $export_frequency)

    <input type="checkbox" name="{{$export_frequency->name}}" id="{{$export_frequency->id}}" value="{{$export_frequency->name}}">
    {{$export_frequency->name}} <br>

    @endforeach

enter image description here

In my Controller (CatalogDownloadController.php)

public function store()
    {

        $catalog_download        = new CatalogDownload;
        $catalog_download->title = Input::get('title');
        $catalog_download->save();

        foreach(ExportFrequency::all() as $export_frequency ){

            $export_frequency_id = Input::get($export_frequency->name);

            if(is_array($export_frequency_id))
            {
                $catalog_download->export_frequencies()->sync([$export_frequency_id, $catalog_download_id]);
                $catalog_download_id = $catalog_download->id;
            }
        }

        return Redirect::to('catalog_downloads/')
        ->with('success','The catalog_download was created succesfully!');

}

Goal

Again, I just want to sync : $export_frequency_id, $catalog_download_id to my catalog_download_export_frequency table.

Question

Can someone tell me what I missed ? The result won't sync. Feel free to give me suggestions/advice on this. Thanks for your time.

Upvotes: 0

Views: 59

Answers (1)

Gareth Daine
Gareth Daine

Reputation: 4186

This should do it mate:

// Your form view
{{ Form::label('export_frequencies' , 'Export Frequencies', array('class'=> 'required cool-blue'))}} <br />
@foreach ($exportFrequencies as $exportFrequency)
    <input type="checkbox" name="export_frequencies[]" id="{{ $exportFrequency->id }}" value="{{ $exportFrequency->id }}">
    {{ $exportFrequency->name }}<br />
@endforeach

// Your store method
public function store()
{
    $input = Input::except('export_frequencies');
    $exportFrequencies = Input::get('export_frequencies'); // Use get, not only

    $catalogDownload = $this->catalogDownload->create($input); // Using dependency injection here, so don't forget to assign your CatalogDownload model to $this->catalogDownload in your contructor

    if (isset($exportFrequencies)
    {
        $catalogDownload->exportFrequencies()->attach($exportFrequencies);
    }

    return Redirect::to('catalog-downloads')->with('success', 'The Catalog Download was created successfully!');
}

Upvotes: 1

Related Questions