0

I use Laravel as Backend and generate API by JSON and the i use php to get json data and delete data by route api in laravel but it's seem to be not working. My API Route in laravel

Route::delete('articles/{article}', 'ArticleController@delete');

My Controller

public function delete(Article $article)
{
    $article->delete();
    return response()->json(null);
}

My API URL

http://192.168.0.21/api/articles/id

My PHP frontend Code for delete

$json = file_get_contents('http://192.168.0.21/api/articles/' . $id);
$json_data = json_decode($json, true);
unset($json_data['id']);

Any solution for these?

Ankit Mishra
  • 130
  • 11
The Rock
  • 323
  • 1
  • 9
  • 23

2 Answers2

4

Route Pass id in the {id}, id of the record you want to delete.

Route::delete('articles/{id}', 'ArticleController@delete');

ArticleController

public function delete($id) {
    $article = Article::findOrFail($id);
    if($article)
       $article->delete(); 
    else
        return response()->json(error);
    return response()->json(null); 
}

AJAX CALL

        $.ajax({
            url: BASE_URL + '/articles/'+ id,
            type: 'DELETE',
        })
        .done(function() {
            console.log("success");
        })
        .fail(function() {
            console.log("error");
        })
        .always(function() {
            console.log("complete");
        });
Jigs1212
  • 673
  • 7
  • 19
2

You set the route method to DELETE but you're requesting it using file_get_contents which is GET.

You need to use curl:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://192.168.0.21/api/articles/' . $id);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result = json_decode($result);
curl_close($ch);
StyleSh1t
  • 548
  • 1
  • 9
  • 18