1

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
  • 393
  • 3
  • 12
  • 29

4 Answers4

8

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
  • 773
  • 8
  • 20
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
  • 717
  • 1
  • 12
  • 18
1

Just wanted to add an alternative to Jigs1212's answer.

Article::findOrFail($id) requires a table type with a column that has a primary key named id.
So, if you have a primary key with a column name other than id, then you cannot use the $article->delete();. Because this will cause error

> BadMethodCallException: Method
> Illuminate\Database\Eloquent\Collection::delete does not exist

We have to change the way to find the id and delete it like this:

Routes

Route::delete('barang_delete', [BarangController::class, 'delete']);

Controller

public function delete(Request $request)
{
    $kode = $request->input('kode');

    $barang = Barang::where('kode', $kode)->get();

    if (!$barang->isEmpty()) {
        Barang::where('kode', $kode)->delete();
        return ResponseFormatter::success(null, 'Barang berhasil dihapus');
    } else {
        return ResponseFormatter::error(null, 'Barang gagal dihapus', 404);
    }
}
Muhammad Faisal
  • 734
  • 10
  • 24
0

Sometimes errors occur when calling api route then the solution by run this command:

 php artisan route:cache
Abdallah
  • 79
  • 1
  • 7