简体   繁体   中英

Send data from Ajax to Laravel controller. Vuejs

I have a little moment that I don't understand because I'm new to development. I'm collecting data from multi step form and want to handle all form inputs at one ajax request on my controlle. I did it successfully, but can't figure out how to use data from $request if it's an array from ajax. I can use if it $request->input('name') but in my case I need something like $request->input('firstGrant.issue_date') because of my data format. Please tip me which way to dig.

My method:

submitCompany() {
 axios.post('/onboarding', {
    name: this.step1.name,
    type: this.step1.type,
    shares_amount: this.step2.shares_amount,
    par_value: this.step2.par_value,
    firstGrant: {
        issue_date: this.step3.firstGrant.issue_date,
        certificate: this.step3.firstGrant.certificate,
        share_price: this.step3.firstGrant.share_price,
        shares_amount: this.step3.firstGrant.shares_amount
    }

})
.then(function (response) {
    console.log(response);
    alert('Information saved!');
})
.catch(function (error) {
    console.log(error);
    alert('Wrong!');
});
}

My Controller:

public function store(Request $request)
{
    $userId = Auth::user()->id;
    $issueDate = $request->input('firstGrant.issue_date'); //How to do it right way?
    $certificate = $request->input('firstGrant.certificate');//How to do it right way? 
    $sharePrice = $request->input('firstGrant.share_price');//How to do it right way?
    $sharesAmount = $request->input('firstGrant.shares_amount');//How to do it right way?

    $equityGrant = EquityGrant::create([
        'user_id' => $userId,
        'share_id' => 91,
        'vesting' => 0,
        'status' => 'active',
        'issue_date' => $issueDate,
        'certificate' => $certificate,
        'share_price' => $sharePrice,
        'shares_amount' => $sharesAmount,
    ]); }

You might have to configure axios to send a header along with every request that will make Laravel recognize the request as being XHR. Once it does, the $request->input('x.y') statements should work.

Object.assign(axios.defaults.headers, {
    'X-Requested-With': 'XMLHttpRequest',
});

If this still does not work you might also want to check whether axios properly includes the CSRF-token in a request header.

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