0

While inserting data into Mysql I have encountered the following error:

"Add [0] to fillable property to allow mass assignment on [App\Models\posts]"

Here is my code:

public function update(Request $request, $id){
        posts::where('id', $id)->first()->update([
            $this->validate($request, [
                'title' => 'required|max:25',
                'description' => 'required|max:255',
                'price' => 'required',
            ])
        ]);

        return redirect(route('posts'));
    }

When adding this to the model some other error occures

protected $guarded = [];  

new errorcode: "SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: update posts set 0 = {"title":"Auto","description":"hallo, das ist eine Beschreibung","price":"123"}, posts.updated_at = 2022-12-26 01:56:20 where id = 1)"

lolich
  • 23
  • 3
  • 3
    you are passing an array inside an array to `update` ... `validate` already returns an associative array of the data, you are then wrapping it in a new array (which only has 1 element and the index is `0`) – lagbox Dec 26 '22 at 02:39
  • Does this answer your question? [Add \[title\] to fillable property to allow mass assignment on \[App\Post\]](https://stackoverflow.com/questions/53793841/add-title-to-fillable-property-to-allow-mass-assignment-on-app-post) – Abdulla Nilam Dec 26 '22 at 05:17
  • https://stackoverflow.com/questions/22279435/what-does-mass-assignment-mean-in-laravel – Abdulla Nilam Dec 26 '22 at 05:17

2 Answers2

2

$this->validate returns an array; there is no need to add another array around it; try this instead:

public function update(Request $request, $id)
{
    posts::where('id', $id)->first()->update(
        $this->validate($request, [
            'title' => 'required|max:25',
            'description' => 'required|max:255',
            'price' => 'required',
        ])
    );

    return redirect(route('posts'));
}
Ali Raza
  • 842
  • 7
  • 13
0

Just figured it out. It should be:

    class posts extends Model
{
    use HasFactory;
    
    protected $fillable = ['title','description', 'price'];
}
lolich
  • 23
  • 3
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 26 '22 at 09:48