PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, January 25, 2022

[FIXED] Getting bulk update to work in laravel 5.6

 January 25, 2022     eloquent, laravel, laravel-5, laravel-5.6, php     No comments   

Issue

My app is being made in laravel 5.6

Situation: I have a table called "members" with a column called "membershipstatus_id". options for status are 4, 5 and 1
4 = Active, 5 = pending and 1= expired

Target: I want to update all active(4) members to pending(5) and all pending ones to expire(1).

Solutions I have tried: So far, below is what i have tried with no result.

    // get all active and pending members        
    $members = Member::where('membershipstatus_id', 5)
                ->orWhere('membershipstatus_id', 4)
                ->get();


    // bulk update with chunk of 200, if this is possible
    $members->chunk(200, function($members)
    {


        foreach($members as $member)
        {

            // if status is pending, update to expire
            if($member->membershipstatus_id == 5)
            {
              $member->update(['membershipstatus_id' => 1]);
             }
            // if status is active, update to pending, i updated a small mistake here. 
            if($member->membershipstatus_id == 5)
            {
              $member->update(['membershipstatus_id' => 4]);
             }


        }
    }
 );

return "update confirm";

Now, If anyone has a cleaner and swift way to do this, Please let me know, also, Im sure i have made some stupid mistake up there. Please point me to the right direction.

Ashish


Solution

Use the query builder like:

// update pending to expired
DB::table('members')
    ->where('membershipstatus_id', 5)
    ->update(['membershipstatus_id' => 1]);

// update active to pending
DB::table('members')
    ->where('membershipstatus_id', 4)
    ->update(['membershipstatus_id' => 5]);


Answered By - Brian Lee
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing