Reputation: 133
I'm new to Laravel. I am trying to create a common social network. Now I want to be able to delete a user's post. At the moment when you try to submit the form it loads the ajax but can not delete the data.
Here is my code:
$("#_global_modal").delegate('#modal_form_delete', 'submit',
function(event)
{
// To stop a form default behaviour
event.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
dataType: 'json',
data: $(this).serialize(),
})
.done(function(response){
if(response.delete == "success"){
window.location.href = response.redirect_route
}else{
console.log(response);
}
})
.fail(function(){
console.log("error");
})
.always(function(){
console.log("complete");
});
});
Route:
Route::post('delete','crude@delete')->name('delete');
My controller part:
public function delete(Request $request)
{
if($request->ajax()){
$user = Auth::user();
$user->post()->delete(['post' => $request->post]);
return response()->json([
'delete' => 'success',
'redirect_route' => route('profile')
]);
}else{
return response()->json([
'delete' => 'ERROR',
'ERROR_MSG' => 'ERROR MSG'
]);
dd("Sorry you have to send your form information by using ajax
request");
}
}
So how can I solve this problem?
Upvotes: 1
Views: 325
Reputation: 11906
Your delete statement is wrong.
public function delete(Request $request)
{
if($request->ajax()) {
Post::where('id', $request->post)
->where('user_id', auth()->id())
->delete();
return response()->json([
'delete' => 'success',
'redirect_route' => route('profile')
]);
}
return response()->json([
'delete' => 'ERROR',
'ERROR_MSG' => 'ERROR MSG'
]);
}
Upvotes: 1