Home > Back-end >  How do save all request data to database
How do save all request data to database

Time:01-08

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...

CodePudding user response:

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()
));

CodePudding user response:

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

CodePudding user response:

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

  •  Tags:  
  • Related