lukeboy_2002's avatar

...$data in [model]::create

Hi,

I want to now what the differece is between

$data = $request->validate([
 		'body' => ['required', 'string', 'max:250']]
 );
		
[Model]::create([
      ...$data,
      'post_id' => $post->id,
      'user_id' => $request->user()->id,
])

[Model]::create([
      'body' => $data,
      'post_id' => $post->id,
      'user_id' => $request->user()->id,
])

both methods passes the test The second one gives a error in use;

the given error is: Illuminate\Database\Grammar::parameterize(): Argument #1 ($values) must be of type array, int given, called in /Users/users/Sites/build_a_forum_with_laravel_2023/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php on line 1131

I use laravel 11

0 likes
1 reply
LaryAI's avatar
Level 58

The error you're encountering is due to the way you're passing the $data variable to the create method in the second example. Let's break down the difference between the two snippets you've provided.

In the first snippet:

$data = $request->validate([
    'body' => ['required', 'string', 'max:250']
]);

[Model]::create([
    ...$data,
    'post_id' => $post->id,
    'user_id' => $request->user()->id,
]);

You are using the spread operator (...) to expand the $data array into individual elements. This means that each key-value pair in the $data array will be passed as a separate argument to the create method. Since $data is an associative array with the keys as the column names and the values as the corresponding values to be inserted, this works perfectly.

In the second snippet:

[Model]::create([
    'body' => $data,
    'post_id' => $post->id,
    'user_id' => $request->user()->id,
]);

You are trying to assign the entire $data array to the 'body' key. This is incorrect because $data is an array and 'body' expects a string (since you've validated it as a string). This is why you're getting the error:

Illuminate\Database\Grammar::parameterize(): Argument #1 ($values) must be of type array, int given, called in /Users/users/Sites/build_a_forum_with_laravel_2023/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php on line 1131

The parameterize method expects an array, but because of the incorrect assignment, it's receiving an integer (or some other non-array type) when it tries to process the 'body' field.

To fix the second snippet, you should extract the 'body' value from the $data array and assign it directly, like so:

[Model]::create([
    'body' => $data['body'],
    'post_id' => $post->id,
    'user_id' => $request->user()->id,
]);

This way, you're correctly passing a string to the 'body' key, and the rest of the fields are assigned as they were before. This should resolve the error and work as expected.

1 like

Please or to participate in this conversation.