There is page with url mysite/dashboard
with the lists of the posts
route
Route::get('dashboard', 'DashboardController@index');
method
public function index() {
$posts = Post::latest('published_at')->unpublished()->paginate(20);
return view('dashboard.index', compact('posts'));
}
every post in the list has button Publish
<button type="button" class="btn btn-primary btn-publish-post">Publish</button>
route for method
Route::post('publish', 'PostsController@publish');
js script
$(document).on('click', '.btn-publish-post', function(){
var $btn = $(this);
var post_id = $(this).closest('.post').data('post-id');
$btn.prop('disabled', true);
$.ajax({
type: 'post',
url: 'publish',
data: {'id' : post_id},
dataType: 'json',
success: function(response){
if(response.success) {
$btn.closest('.post').remove();
}
if(response.fail) {
}
$btn.prop('disabled', false);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
$btn.prop('disabled', false);
}
});
});
method in PostsController
public function publish(Request $request)
{
$id = $request->get('id');
$published = Post::where('id', $id)
->update(['is_published' => 1]);
if ($published) {
return Response::json(array(
'success' => true
));
}
return Response::json(array(
'fail' => true
));
}
For every post in the list all code works just fine.
But also I can open every one post
route
Route::get('dashboard/posts/{id}', 'DashboardController@show');
method in DashboardController
public function show($id) {
$post = Post::findOrFail($id);
return view('dashboard.show', compact('post'));
}
and the post also has Publish button, but for one post js code doesn't work becase it tries to send AJAX request to url mysite/dashboard/posts/publish
(not mysite/publish
) and of couse fails. How to make my code works for the list of the posts and for one post both?
via Heidel