Chonchol Mahmud
Chonchol Mahmud

Reputation: 2735

How to update specific column data at a time by Laravel 5.2?

I have a users table where i have a column named rank_id. Now i want to update all users rank_id into 2 where rank_id = 6 at a time(click by one button). How can i do that? I have tried so far:

Routes:

Route::post('/test/rankup2', array('as' => 'user.rank2.post', 'uses' => 'TestController@RankUpgradeTwo'));

TestController.php:

function RankUpgradeTwo(Request $request)
{
    $memberAll = User::where('rank_id','=',6)->firstOrFail();
    //dd($memberAll);

    $memberAll->rank_id = '2';

    $memberAll->save();
    return Redirect::to('user/test')->with('message', 'Successfully Ugraded into Rank 2');

}

testScript.blade.php:

    <form method="POST"
        action="{{ route('user.rank2.post') }}"
        class="form-horizontal stdform"
        autocomplete="off"
        enctype="multipart/form-data"
        id="edit-form"
        role="form"
        {{--v-on:submit="submitChange" --}}
        novalidate />
    {{ csrf_field() }}


<div class="control-group action">


    <button type="submit" name="submit" value="submit" id="submit" class="btn btn-blue btn-left">
       Rank Up 2
    </button>       

</div>

{{ Form::close() }}

This shows me successfull message but i don't see any update in database. Thanks in advance.

Upvotes: 0

Views: 4250

Answers (1)

Basheer Kharoti
Basheer Kharoti

Reputation: 4302

You can try Eloquent Update

User::where('rank_id','=',6)->update(['rank_id' => 2]);

OR

Since firstOrFail will just fetch the first record from the db so you won't be able to update all the records but there is another work around for that e.x

$memberAll = User::where('rank_id','=',6)->get();
foreach($memberAll as $member) {
    $member->rank_id = 2;
    $member->save();
}

Upvotes: 2

Related Questions