Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to store array of value in database records in laravel

store in array format
store in key value pair using json_encode

store in array format

get the collection of records
array of 'influencer_admin_id' values from the records in the $pay_users collection using pluck
store this array of value using json_encode in database

Step 1:get the collection of records

$pay_users = addcart::where('admin_id', $param3)->get();
Enter fullscreen mode Exit fullscreen mode

step2: store the array of 'influencer_admin_id' values from the records in the $pay_users collection.

$influencer_adminids = $pay_users->pluck('influencer_admin_id')->toArray();
Enter fullscreen mode Exit fullscreen mode

output

$influencer_adminids = ['123', '456', '789'];
Enter fullscreen mode Exit fullscreen mode

or

[2023-10-31 05:24:30] local.INFO: array (
  0 => 123,
  1 => 456,
)  
Enter fullscreen mode Exit fullscreen mode

step3:store this array of value in database

    $Paytm = new Paytm;
       // $Paytm->influencer_admin_id = implode(',', $influencer_adminids);
       $Paytm->influencer_admin_id = json_encode($influencer_adminids);
        $Paytm->influencer_email = json_encode($influencer_email) ;
        $Paytm->influencer_name = json_encode($influencer_name) ;
        $Paytm->cart_id = json_encode($cart_id);
        $Paytm->payment_id = $param1;
        $Paytm->amount = $param2;
        $Paytm->payment_status ="approved";
        $Paytm->admin_id = $param3;
        $Paytm->user_name = $param4;
        $Paytm->Pay_date = $param5;
        $Paytm->org_slug = $param6;
        $Paytm->admin_email = $param7;
        $Paytm->created_at = $param8;
        $Paytm->save();
Enter fullscreen mode Exit fullscreen mode

output

Image description

store in json format

Encode the array into JSON format
store the encoded variable
data is in associative array format when comes through request or define satatically

use Illuminate\Database\Eloquent\Model;

class YourModel extends Model
{
    protected $fillable = ['socialsite'];

    public function storeData()
    {
        // Data to be stored in JSON format
        $data = [
            'facebook' => 50,
            'twitter' => 30,
            'utube' => 80,
        ];

        // Encode the array into JSON format
        $jsonData = json_encode($data);

        // Store the data in the database
        YourModel::create([
            'socialsite' => $jsonData,
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

in phpmyadmin
{"facebook": 50, "twitter": 30, "utube": 80}

Top comments (0)