Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cola's avatar
Level 1

How can I save request data into database at once?

What I did:

        $obj=new User();
        $obj->first_name=$request->input('firstName');
        $obj->last_name=$request->input('lastName');
        $obj->email=$request->input('email');
        $obj->password=bcrypt($request->input('password'));
        $obj->save();

Is it possible to do something in this way instead of getting single input by $request->input()?

        $obj=new User();
        $obj->save($request->all());
0 likes
6 replies
tisuchi's avatar

@cola You can. But you need to change a few things-

User::create($request->only(['firstName', 'lastname', 'email', 'password']));

Now in your model, make sure that you allow mass assignment.

User.php

protected $guarded = [];

// This for password bcrypt. 
public function setPasswordAttribute($value){
	$this->password = bcrypt($value);
}
cola's avatar
Level 1
User::create($request->only(['firstName', 'lastname', 'email', 'password']));

How will 'firstName' map with $obj->first_name column?

Tray2's avatar

I use the same name for my form element and my column name, that way I never have to worry about it.

Tray2's avatar

You should also validate the data before inserting anything.

Snapey's avatar

if your variable is a user then call it $user not $obj - it makes your code easier to understand

Yes, you can mass assign an array to a model, but pay attention to name your form fields exactly the same as the columns on your database. If you don't do this then you need to map each field across manually.

Personally I avoid mass assignment. I prefer to be explicit in my code, and it also gives opportunity to give special treatment to individual columns as they are saved

Please or to participate in this conversation.