Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type error: Argument 1 passed to Illuminate\Database\Eloquent\Builder::create() must be of the type array, null given

i am trying to post title and article in laravel rest api i am getting this error

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

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

And this store function of ArticleController.php file

 public function store(Request $request)
    {
        $article = Article::create($request->all());

        return response()->json($article, 201);
    }

This is article model class

class Article extends Model
{
    //new
    protected $fillable = ['title', 'body'];
}

i tried change this in articlecontroller file but getting same error

$article = Article::create($request->only([
            'title',
            'body']));

How can I solve this issue?

like image 776
Raikumar Khangembam Avatar asked Nov 07 '17 09:11

Raikumar Khangembam


2 Answers

As #Masivuye_Cokile suggested me, i modified my code in route and controller function and it fixed my problem.

Route/api.php

Route::post('articles', function(Request $request) {
    $data = $request->all();
        return Article::create([
            'title' => $data['title'],
            'body' => $data['body'],
        ]);
});

In Controller function

 public function store(Request $request)
    {
       $article = Article::save();
       return response()->json($article, 201);
    }
like image 108
Raikumar Khangembam Avatar answered Nov 17 '22 14:11

Raikumar Khangembam


I know there's an accepted answer already, but I don't think the reason for the error was clearly explained.

If you take a look at your code below, you'll notice there's an error on the second route definition as you typed; $request->all instead of $request->all()

Route::post('articles', 'ArticleController@store');

Route::post('articles', function(Request $request) {
   return Article::create($request->all);
});

So, I think a simpler solution would be:

Route::post('articles', 'ArticleController@store');

Route::post('articles', function(Request $request) {
   return Article::create($request->all());
});
like image 1
rogramatic Avatar answered Nov 17 '22 12:11

rogramatic