So I'm trying CRUD using laravel collective, my problem is how to get the id of a selected row in order to edit it.
it looks like if i select a certain column i want to edit in my table, the id that it gets is the id of the last row instead of the selected row.
Here's my view.
<table class="table">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Course</th>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach ($cruds as $crud)
<tr>
<th scope="row">{{$crud->id}}</th>
<td>{{$crud->firstName}}</td>
<td>{{$crud->lastName}}</td>
<td>{{$crud->course}}</td>
<td><button class= "btn btn-warning" data-toggle="modal" data-target="#editModal"> Edit </button></td>
<td><button class= "btn btn-danger" data-toggle="modal" data-target="#deleteModal"> Delete </button></td>
</tr>
@endforeach
</tbody>
</table>
here's my modal
{{-- <-- Edit Modal --> --}}
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">EDIT DATA</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{!! Form::open(['action' => ['CrudController@update', $crud->id], 'method' => 'POST'])!!}
<div class="form-group">
{{Form::label('firstName','First Name')}}
{{Form::text('firstName',$crud->firstName,['class' => 'form-control'])}}
</div>
<div class="form-group">
{{Form::label('lastName','Last Name')}}
{{Form::text('lastName',$crud->lastName,['class' => 'form-control'])}}
</div>
<div class="form-group">
{{Form::label('course','Course')}}
{{Form::text('course',$crud->course,['class' => 'form-control'])}}
</div>
<div class="modal-footer">
{{Form::hidden('_method', 'PUT')}}
{{Form::submit('Update', ['class' => 'btn btn-primary'])}}
</div>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
here's my controller
public function update(Request $request, $id)
{
//
$this->validate($request, [
'firstName' =>'required',
'lastName' => 'required',
'course' => 'required'
]);
//Adding Data
$crud = Crud::find($id);
$crud->firstName = $request->input('firstName');
$crud->lastName = $request->input('lastName');
$crud->course = $request->input('course');
$crud->save();
return redirect('/crud');
}
try this
<script>
$(document).on('click', '.edit-modal', function() {
$('#id').val($(this).data('id'));
$('#firstName').val($(this).data('firstName'));
$('#lastName').val($(this).data('lastName'));
$('#course').val($(this).data('course'));
$('#ModalEditForm').modal('show');
});
</script>
and give each input an ID, and send the id of record as hidden input remove the id from the route and the controller method and send the id as hidden input