skip to Main Content

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

"Add [0] to fillable property to allow mass assignment on [AppModelsposts]"

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)"

2

Answers


  1. Chosen as BEST ANSWER

    Just figured it out. It should be:

        class posts extends Model
    {
        use HasFactory;
        
        protected $fillable = ['title','description', 'price'];
    }
    

  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'));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search