0
$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?

1
  • 1
    if you're happy with my answer below, you can accept it :) Commented Apr 18, 2015 at 13:45

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Insert won't add created_at and updated_at time. That's need to be added manual. :)
$input[activities] contains array of values which needs to be inserted without using the foreach in separate rows.
3

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.