Home > Mobile >  How can I pass RESULT from javascript to laravel function as amount?
How can I pass RESULT from javascript to laravel function as amount?

Time:07-14

I want to save this result as amount, when I do console.log(result); I see that know what number I put in input, but how to save it in Laravel function?

 function makeOffer(nftid) {
                    swal({
                        title: "Do you want to make offer?",
                        text: "Enter amount",
                        input: 'text',
                        type: 'warning',
                        showCancelButton: true,
                        showConfirmButton: true,
                        confirmButtonColor: '#3085d6',
                        cancelButtonColor: '#d33',
                    }).then((result) => {
                        if (result) {
    
                            axios.post("/myaccount/makeoffer/"   nftid).then(response => {
                                window.location.reload();
                            });
                        }
                    });
                }
    
    public function makeOffer($id, Request $request){
    
            $nft=NFT::where('id','=',$id)->first();
            if($nft->status=='pending') {
                $nft_auction = new NftAuctions();
                $nft_auction->nft_id = $nft->id;
                $nft_auction->owner_id = $nft->user->id;
                $nft_auction->buyer_id = Auth::id();
                $nft_auction->amount = "there should be amount";
                $nft_auction->status = 'pending';
                $nft_auction->save();
                return back();
            }
            else{
                abort(404);
            }
            
        }

CodePudding user response:

Axios' .post() method takes 2 arguments; the URL and the data you want to send to the backend, so adjust it to:

axios.post("/myaccount/makeoffer/"   nftid, {'amount': result})
.then(response => {
  window.location.reload();
});

Then, in your backend, you can access this as $request->input('amount'):

public function makeOffer($id, Request $request){
  $nft = NFT::find($id);

  if($nft->status == 'pending') {
    $nftAuction = new NftAuctions();
    // ...
    $nftAuction->amount = $request->input('amount');
    // ...
    $nftAuction->save();

    return back();
  }  
}

Some notes:

  1. Model::where('id', '=', $id)->first() can be shortened to Model::find($id).
  2. Model names are PascalCase and singular: NFT should be Nft, and NftAuctions should be NftAuction

Documentation:

Axios .post() method

Laravel: Retrieving Input

  • Related