I want to build a video streaming web app. I want to keep track of the videos watched by users. When the video is started, it will be added to the database table called "watches". I have 3 tables for this operation. Persons table:
->person_id
->name
->email
->password
Contents table:
->content_id
->title
->content_type
Watches table:
->watch_id
->person_id(foreign key)
->content_id(foreign key)
When the play button will be triggered, it will add to the database. How can I do that?
What you can do is listen for click event on the Play Button. You can achieve that with either JavaScript or some JavaScript framework like jQuery (if you are already using it in your project). I'll show you the jQuery way as it's more modern.
First of all you must create a new route which will use the Route Model Binding technique.
use App\Models\ContentModel;
use App\Models\WatchModel;
use Illuminate\Http\Request;
Route::post('increment/{content:content_id}/watches', function(Request $request, ContentModel $content) {
if($request->ajax()) {
if(WatchModel::where('person_id', '=', auth()->user()->id)
->where('content_id', '=', $content->content_id)
->doesntExists()) {
$insert = WatchModel::insert([
'person_id' => auth()->user()->id,
'content_id' => $content->content_id
]);
if($insert) {
return response()->json('Successfully incremented the watches!', 200);
}
}
}
})->whereNumber('content');
Then you attach a click event listener to the button and perform an AJAX request to the route we just created.
$("#playButton").on('click', function() {
$.ajax({
'url' : 'https://yoursite.com/increment/{{ $content->content_id }}/watches',
'type' : 'POST',
'data' : {
'user_id' : {{ auth()->user()->id }}
}
});
});
And that's it! You can upgrade the code with some logic based on your needs. I personally would create some logic to check for first button click and avoid sending AJAX request to the server on each click but that's up to you.