HammockKing
HammockKing

Reputation: 77

Laravel/php: Looped value only sending last value

I know this is a simple one but I have a loop which only gives me back the last value of my ID as so:

@foreach($users as $user)
        <tr>
            <td>{{{$user->firstname}}}</a></td>
            <td>{{{$user->secondname}}}</a></td>
            <td>{{{$user->address}}}</a></td>
            <td>{{{$user->city}}}</a></td>
            <td>{{{$user->phone}}}</a></td>
            <td>{{{$user->id}}}</td>
            <td>{{{$user->username}}}</a></td>
            <td>{{{$user->email}}}</tds>
            <td>{{{$user->type}}}</a></td>
            <td><input type="submit" name="Approve" value="Approve"></td>
            <td><input type="submit" name="Decline" value="Decline"></td>
            <label><span></span>{{Form::hidden('user_id', $user->id);}}</label>


        </tr>
    @endforeach

Its a form in a loop which produces two buttons which either approves or declines members. The last list I.E.

{{Form::hidden('user_id', $user->id);}}

sends back the user_id to the controller but of course it only sends the last id as its being overwritten every time no matter which button is pressed. Initially I created an iterated i.e $i and added it to user_id in the above piece of code; such as 'user_id'.$i. This is perfectly fine until I get to the controller and if I do not know the iterated number then there is no point in sending the user_id in the first place. All help appreciated. Thanks.

edit1: added controller. What I am actually trying to do above is iterate through the results properly

public function postUpdate() {
        $uid = Input::get('user_id');
        //checking which submit was clicked on
        if(Input::get('Approve')) {
            $this->postApprove($uid); //if approved then use this method
        } elseif(Input::get('Decline')) {
            $this->postDecline($uid); //if declined then use this method
        }


    }

Upvotes: 0

Views: 292

Answers (1)

Sam
Sam

Reputation: 20486

Probably will want to make multiple forms, so something like this (psuedo-code):

@foreach($users as $user)
    <tr>
        {{Form::open()}}
            <td>{{-- user info --}}</td>

            <td><input type="submit" name="action" value="Approve"></td>
            <td><input type="submit" name="action" value="Decline"></td>

            {{Form::hidden('user_id', $user->id)}}
        {{Form::close()}}
    </tr>
@endforeach

Now in your controller you can do something like this:

$user = User::find(Input::get('user_id'));
switch(Input::get('action') {
    case 'Approve':
        // $user is approved
        break;
    case 'Decline':
        // $user is declined
        break;
    default:
        // Not submitted
}

Notice, I also made both submit buttons have the name="action" so all we have to do is check what the value of Input::get('action') is.

Upvotes: 2

Related Questions