类型错误:传递给Illuminate \ Database \ Eloquent \ Builder :: create()的参数1必须为数组类型,给定null [英] Type error: Argument 1 passed to Illuminate\Database\Eloquent\Builder::create() must be of the type array, null given
问题描述
我试图在laravel rest api中发布标题和文章,但出现此错误
i am trying to post title and article in laravel rest api i am getting this error
类型错误:参数1传递给 Illuminate \ Database \ Eloquent \ Builder :: create()必须为以下类型 数组,给定null,在中调用 C:\ xampp \ htdocs \ LaravelProject \ cpapi \ vendor \ laravel \ framework \ src \ Illuminate \ Database \ Eloquent \ Model.php 在1440行上
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Builder::create() must be of the type array, null given, called in C:\xampp\htdocs\LaravelProject\cpapi\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php on line 1440
这是我的文章数据的route/api.php文件
This is my route/api.php file of post article data
Route::post('articles', 'ArticleController@store');
Route::post('articles', function(Request $request) {
return Article::create($request->all);
});
还有ArticleController.php文件的此存储功能
And this store function of ArticleController.php file
public function store(Request $request)
{
$article = Article::create($request->all());
return response()->json($article, 201);
}
这是文章模型类
class Article extends Model
{
//new
protected $fillable = ['title', 'body'];
}
我尝试在articlecontroller文件中更改此设置,但出现相同的错误
i tried change this in articlecontroller file but getting same error
$article = Article::create($request->only([
'title',
'body']));
我该如何解决这个问题?
How can I solve this issue?
推荐答案
按照#Masivuye_Cokile的建议,我修改了路由和控制器功能中的代码,并解决了我的问题.
As #Masivuye_Cokile suggested me, i modified my code in route and controller function and it fixed my problem.
Route/api.php
Route/api.php
Route::post('articles', function(Request $request) {
$data = $request->all();
return Article::create([
'title' => $data['title'],
'body' => $data['body'],
]);
});
在控制器功能中
public function store(Request $request)
{
$article = Article::save();
return response()->json($article, 201);
}
这篇关于类型错误:传递给Illuminate \ Database \ Eloquent \ Builder :: create()的参数1必须为数组类型,给定null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!