I need some help in implementing a basic ajax request through vue to my laravel back-end, I have a boolean named completed on a table called courses, and I have a view that fetches all courses assigned to a specific user and allows them to press a button to change the current status of the course, either completed or not, that's it, that's all I wanna do, right now I'm half way there, I can submit the ajax request but it only grabs the last course that was fed to the view, I know this will eventually turn out to be a mistake from my end that I can't see, so please be explicit in your solution,
The relevant part of the CoursesController:
public function toggling($name)
{
$course = Course::where(['name' => $name])->first();
$course->completed = !$course->completed;
$course->save();
return response()->json(['course' => $course], 202);
}
The Vue instance which is set on the main layout page(If this is a mistake please point that out):
<script>
new Vue({
el: '#app',
data: {
course: {
name: ''
}
},
methods: {
onSubmit: function($course) {
this.course.name = '{{$course->name}}',
axios.post('/MyCourses/' + this.course.name);
// .then(function (response){
// });
}
}
});
</script>
The form part of the view responsible of rendering the courses:
<tbody>
@foreach ($courses as $course)
<tr>
<td>{{ $course->name }}</td>
<td>{{ $course->appointment }}</td>
<td>{{ $course->room_id }}</td>
<td>
<form method="POST" action="{{ route('course.completed', $course->name) }}" id="form-submit">
{{ csrf_field() }}
@if ($course->completed == true)
<button @click.prevent="onSubmit" type="button" class="btn btn-sm" id="coursetogglingtrue">Done!</button>
@else
<button @click.prevent="onSubmit" type="button" class="btn btn-sm" id="coursetogglingfalse">Not Yet!</button>
@endif
</form>
</td>
</tr>
@endforeach
</tbody>
If you have time I'd appreciate if you can help make this dynamic by binding the id of the divs to the appropriate class based on the status of the course, I cannot do that right now, tried and failed to do an if condition inside the Vue instance.
And this is the one route responsible for the request from web.php:
Route::post('/MyCourses/{name}', 'CoursesController@toggling')->name('course.completed');
Right now, let's say I have 4 courses on my page, If I pressed on any button, only the last course would be provided to the vue instance regardless of which button I pressed, I'm guessing it is probably the structure of my view is what's wrong, I'd like to know what's causing the problem, also my other pages are errorring out because they don't have an access to a $course object, which is why I assume that having all of this on the main Vue instance is a big no-no, once again, whatever ideas/tips/recommendations you have on the problem or on my code please let me know, thanks.