我正在尝试在Laravel中创建自己的资源API,我通过Postman程序测试了api,index()和show()函数(带有GET请求)运行良好,但是很不幸地store()/ delete()函数不起作用(POST,PUT,DELETE请求)。
我已经尝试了很多教程,并且结果相同,我无法使用POST,PUT,DELETE请求(或者无法通过Postman对其进行正确测试)
更多详细信息:
1.1 One Category can have many Startups 1.2 One Contact can have many Startups 1.3 One Country can have many Contacts
我在web.php(不是在api.php中)中定义了Api路由,(我正在尝试为Startups Table创建api)
// get list startups
Route::get('api/startups', 'Admin\StartupController@index');
// get single startup
Route::get('api/startup/{id}', 'Admin\StartupController@show');
// create new startup
Route::post('api/startup', 'Admin\StartupController@store');
// update startup
Route::put('api/startup', 'Admin\StartupController@store');
// delete startup
Route::delete('api/startup/{id}', 'Admin\StartupController@destroy');
控制器代码(StartupController),我仅显示一种方法-store() (我认为足以确定问题)
public function store(Request $request) {
$startup = Startup::create([
'category_id' => $request->category()->id,
'contact_id' => $request->contact()->id,
'name' => $request->name,
'description' => $request->description,
'url' => $request->url,
'logo' => $request->logo,
]);
return new StartupResource($startup);
该功能的第二个选项(也无法使用):
public function store(Request $request) {
$startup = $request->isMethod('put') ? Startup::findOrFail($request->startup_id) : new Startup;
$startup->id = $request->input('startup_id');
$startup->name = $request->input('startup_name');
$startup->description = $request->input('startup_description');
$startup->url = $request->input('startup_url');
$startup->logo = $request->input('startup_logo');
if ($startup->save()) {
return new StartupResource($startup);
}
}
我的迁移
Schema::create('startups', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id');
$table->integer('contact_id')->nullable();
$table->string('name');
$table->mediumText('description');
$table->string('url');
$table->boolean('public')->default(false);
$table->string('logo');
$table->timestamps();
});
toArray()函数
public function toArray($request) {
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'url' => $this->url,
'public' => $this->public,
'logo' => $this->logo,
'created_at' => (string) $this->created_at,
'updated_at' => (string) $this->updated_at,
'category' => $this->category,
'contact' => $this->contact
];
}
(其他)可能会有所帮助-我如何在邮递员中进行测试
答案 0 :(得分:0)
我认为这是CSRF保护。
https://laravel.com/docs/5.7/csrf
api.php路由没有此保护(仅web.php)。 因此,您应该决定-使用api路由,还是仅使用VerifyCsrfToken :: $ except属性来避免对某些路由提供这种保护。