0
votes

I'm new in laravel and Javascript.

I have a route which looks like

Route::get('/problems/{problem}/edit', 'AdminController@editProblem');

and my page looks like image

HTML code for this page is

@foreach($in_contest->problems as $problem)
    <div class="list-group">
        <a href="#" class="list-group-item">
            <i class="fa fa-file fa-lg"></i>
            {{ $problem->title }}
            <span class="pull-right">
                <button onclick="callRoute()" class="btn btn-xs btn-info button">Edit</button>
            </span>
        </a>
    </div>
@endforeach

I wrote javascript code for this onclick which is

<script type="text/javascript">
    function callRoute() {
        window.location = '{{ url('/problems/' . $problem->id . '/edit') }}';
    }
</script>

now every time I'm clicking Edit button on P1, P2, or P3 its opening the edit page for P4. Same url is opening for all. I want when I click edit on P1 its redirect to edit page for $problem-id with P1. and same for the others too.

What is the solution of this problem?

2

2 Answers

1
votes

The reason it is calling p4 is that after you have run your foreach loop, you are basically writing the last iteration of problem ID to your javascript.

You can avoid adding blade syntax to your javascript all together by changing your view code to the following so it passes the current problem ID to your javascript function

@foreach($in_contest->problems as $problem)
    <div class="list-group">
        <a href="#" class="list-group-item">
            <i class="fa fa-file fa-lg"></i>
            {{ $problem->title }}
            <span class="pull-right">
                <button onclick="callRoute({{ $problem->id }})" class="btn btn-xs btn-info button">Edit</button>
            </span>
        </a>
    </div>
@endforeach

and your javascript function to the following

<script type="text/javascript">
    function callRoute(problemID) {
        window.location = '/problems/' + problemID + '/edit';
    }
</script>
1
votes

You've 4 results in your page and your callRoute function is outside of your loop so after the loop done it's job the variable $problem you are accessing in your script tag is the last one iterated over the results collection so that's why it's having the id 4

simply just write it like

<button onclick="callRoute({{ $problem->id }})" class="btn btn-xs btn-info button">Edit</button>

and in your script

function callRoute(problem_id) {
    window.location = '/problems/' + problem_id + '/edit';
}