Rajesh Kumar
Rajesh Kumar

Reputation: 247

Laravel, insert multiple rows without using foreach

$input['activities'] = array(3,2,5);

foreach($input['activities'] as $activity_id){

    $user_activities = new User_activities;

    $user_activities->activity_id = $activity_id;

    $user_activities->user_id = Auth::id();

    $user_activities->save();

}

Is it possible to have a single line of script to do the above save for each statement in Laravel ? Instead doing the save in foreach, is it possible to do it in a single line?

Upvotes: 0

Views: 5314

Answers (2)

Rajesh Kumar
Rajesh Kumar

Reputation: 247

I have found the solution,

$activities = array(3,2,5);
$user->activities()->sync($activities);

User model will have the activities function like the following,

public function activities()
{
    return $this->belongsToMany('App\Activity', 'user_activities')->select(['activities.id'])->withTimestamps();
}

Upvotes: 3

Limon Monte
Limon Monte

Reputation: 54389

Just pass array of arrays to Eloquent::insert():

$data = [];

foreach($input['activities'] as $activity_id) {
    $data[] = [
        'activity_id' => $activity_id,
        'user_id' => Auth::id()
    ];
}

Coder::insert($data);

Upvotes: 5

Related Questions