I am using laravel 5.1 and still pretty new to the framework.
When someone adds or updates a new article, I want the page where the article is displayed to be refreshed. Is it possible to do this using some kind of listener or "asking" x amounts of seconds if a update has been made? What would be a good practice to accomplish this? I would appreciate if someone could provide some code examples as well. Thanks!
I suppose this task can be achieved using web sockets but it's a bit overkill for my case since I just want a simple function for this one case.
Hello,
I don't know of any way to achieve this without web sockets. Of course you can make a jquery script to keep posting to an URL but it's not a good practise.
Have you tried Pusher? There is a free tier, and it's really easy to implement:
function updatePost() {
setInterval(function() {
$.ajax({
type: "GET",
url: "posts/1/2015-11-24-00-00-00", // You add the id of the post and the update datetime to the url as well
success: function(response) {
// If not false, update the post
if (response) {
// Update the h2 with the new title from the post
$("#article > h2").html(response.title);
// Update the div with the new body from the post
$("#article > .body").html(response.body);
}
}
});
}, 5000); // Do this every 5 seconds
}
Then in Laravel you do something like this
// Routes.php
Route::get('posts/{id}/{datetime}', 'PostsController@updated');
// PostsController.php
public function updated($id, $datetime)
{
$post = Post::findOrFail($id);
if ($post->updated_at > Carbon::createFromFormat('Y-m-d-H-i-s', $datetime)) {
return $post;
}
return false;
}
Instead of checking the updated_at you check the count of the articles. Or check the updated_at field of the last on the page with the last of the collection of articles. I'm sure you can think of a way to check this ;)
You would create another route with a new method. This route is returning a view. You don't want that in your ajax response. You only want the data in your response
@bobeta You’d be better off implementing a web socket-based solution that only updates a page if the channel it’s listening on receives a message (when you update an article, send a message).
You don’t want to be polling every x seconds because if 1,000 people are on your website, suddenly you’re server’s receiving 1,000 more HTTP requests every x seconds regardless of whether an article’s been published or not.