php - Data is not getting stored in database for multiple check box in laravel

403

I have created a form, in which I have a list of days to be selected multiple. But those days are not getting stored in database.

here is my controller:

public function store(EventRequest $request)
{
    $input = Request::all();
    $input['days_of_week'] = Input::get('days_of_week');
    Event::create($input);
    return redirect('event');
}

and my view is:

    @foreach($days as $day)
    <ul>
        <li>
            {!! Form::checkbox("days_of_week[]", $day, null) , $day !!}
        </li>
    </ul>
    @endforeach

when I returnInput::get('days_of_week'); it displays the check boxes I select.

How can I store checkbox value along with all the other fields present in form.

193

Answer

Solution:

Like Jerodev said, you cannot store array to the database. What you can do is serialize the array and store it. Then when retrieving the value, you can unserialize it.

public function store(EventRequest $request)
{
    $input = Request::all();
    $input['days_of_week'] = serialize(Input::get('days_of_week'));
    Event::create($input);
    return redirect('event');
}

and you can retrive it like this

$daysOfWeek = unserialize(Event::find(1)->days_of_week);
584

Answer

Solution:

You cannot add an array to the values for the database, you will have to split this in seperate fields. I don't know what your database looks like, but here is an example on how to do this.

foreach (Input::get('days_of_week') as $key => $value) {
    $input['day_of_week_' . $key] = $value;
}

People are also looking for solutions to the problem: jquery - Getting error named 'undefine' when i fetch json data from php page to index page

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.