Skip to content

Instantly share code, notes, and snippets.

@tolu360
Created January 8, 2014 16:49
Show Gist options
  • Save tolu360/8319997 to your computer and use it in GitHub Desktop.
Save tolu360/8319997 to your computer and use it in GitHub Desktop.
//app/routes.php
Route::post('favorites', ['as' => 'favorites.store', function()
{
if (Request::ajax()) {
$postId = Input::get('post-id');
$favorites = DB::table('favorites')->whereUserId(Auth::user()->id)->lists('post_id');
if (!in_array($postId, $favorites)) {
Auth::user()->favorites()->attach($postId);
}
return Post::find($postId)->favorites()->count();
//echo "Process ajax request";
} else {
Auth::user()->favorites()->attach(Input::get('post-id'));
return Redirect::back();
}
}])->before('auth|csrf');
//app/views/layout.blade.php
<script>
(function(){
$('.post').on('submit', function(e) {
var that = $(this);
$.ajax({
type: 'POST',
url: '{{ url('favorites') }}',
data: that.serialize()
}).then(function(data) {
that.find('.count').html(data);
that.find('.submit i').removeClass('not-favorited');
that.find('.submit i').addClass('favorited');
})
e.preventDefault();
});
})();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment