简体   繁体   中英

How do save all request data to database

how can save all to Database?

    $request->validate([
        'name' => 'required',
        'email' => 'required',
        'street' => 'required',
        'street_addition' => 'nullable',
        'postal_code' => 'required',
        'city' => 'required',
        'country' => 'required',
        'vat_id' => 'nullable'
    ]);

    $user = Auth::user();

    $billingDetail = $user->billingDetails()->save(new UserBillingDetail([
        $request->all()
    ]));

the $request->all() dont work. idk why. it comes

SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value" and email and and and...

The SQL error you are experiencing is because your columns doesn't allow NULL values and it produces this error, when you try and put in a row with empty values.

The reason why your values are empty, is because you're wrapping your UserBillingDetail construct parameter with an [] :

$billingDetail = $user->billingDetails()->save(new UserBillingDetail([
    $request->all()
]));

This will effectively send an array with a single key ( 0 ) containing the value of your request->all() . Hence, the name , email , etc., fields doesn't exist in the top level array (which is what you want).

You should remove the extra brackets, making your code look like this:

$billingDetail = $user->billingDetails()->save(new UserBillingDetail(
    $request->all()
));

The error message already give you the answear. you pass data and some fields are empty. first of all: make sure that this fills not empty. then check of the fields are declare as fillable in your model. protected $fillable = [...]

Try using $request->except('_token') in place of $request->all() as the request also have _token key in it.

error message already give you the answer. you pass data and some fields are empty. or make the field nullable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM