umutyerebakmaz
umutyerebakmaz

Reputation: 1037

How to Store Array Data Using Laravel foreach with ORM

create_team_social_icons_table.php

        $table->increments('id');
        $table->integer('order_id');
        $table->integer('team_id');
        $table->integer('social_class');
        $table->string('link');

Hello, I have two different array from create form social_class[] and link[]. Trying to record values from a form using the form at one time.

<select name="social_class[]">
<select name="social_class[]">
<select name="social_class[]">
<select name="link[]">
<select name="link[]">
<select name="link[]">

I received an error message:

preg_replace(): Parameter mismatch, pattern is a string while replacement is an array.

        $social_class = Input::get('social_class');
        $link = Input::get('link');
        foreach ($social_class as $socialClass) {
            $tsi = new TeamSocialIcon();
            $tsi->order_id = 0;
            $tsi->team_id = $insertedId;
            $tsi->social_class = $socialClass;
            $tsi->link = $link;
            $tsi->save();
        }

Upvotes: 0

Views: 1832

Answers (2)

umutyerebakmaz
umutyerebakmaz

Reputation: 1037

I replied to myself for my solution

$social_class = $request->social_class;
$link = $request->link;

        for($i = 0; $i < count($social_class); $i++) {
            $tsi = new TeamSocialIcon();
            $tsi->order_id = 0;
            $tsi->team_id = $insertedId;
            $tsi->social_class = $social_class[$i];
            $tsi->link = $link[$i];
            $tsi->save();
        }

Upvotes: 0

Ritesh Lamichhane
Ritesh Lamichhane

Reputation: 43

Try converting the array into string using explode method. You should also change the column data type to string or varchar for the data to be successfully saved. While retrieving the data you can convert the string back into array using implode method.

Upvotes: 1

Related Questions