如何在 Laravel API 路由中使用删除

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49442337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:33:02  来源:igfitidea点击:

How to use Delete in Laravel API Route

phpjsonlaravelapi

提问by The Rock

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

我使用 Laravel 作为后端并通过 JSON 生成 API,我使用 php 获取 json 数据并通过 Laravel 中的路由 api 删除数据,但它似乎不起作用。我在 Laravel 中的 API 路由

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

My Controller

我的控制器

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

My API URL

我的 API 网址

http://192.168.0.21/api/articles/id

My PHP frontend Code for delete

我的 PHP 前端删除代码

$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?

这些有什么解决办法吗?

回答by Jigs1212

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

中的RoutePass id,{id}要删除的记录的id。

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 调用

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

回答by StyleSh1t

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

您将路由方法设置为 DELETE,但您使用 GET 的 file_get_contents 请求它。

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);