Laravel 5.2 ajax update issue - php

I simply cannot get this to work.
What am i doing wrong here? Thanks! :-)
The validator returns fields are requiered, and i cannot seem to access any of the data.
Controller:
public function updateGlobalData(Request $request){
$validator = Validator::make($request->all(), [
'company_name' => 'required',
'adress' => 'required',
'city' => 'required',
'zip' => 'required',
'country' => 'required',
'cvr' => 'required',
'email' => 'required|email',
'phone' => 'required'
]);
$errors = $validator->errors();
if ($validator->fails()) {
return response()->json([
'success' => false,
'message' => $errors
], 422);
}
$globalData = GlobalData::find($request->id)->update($request->all());
$response = [
'status' => 'success',
'msg' => 'Hotel created successfully'
];
// Session::flash('success', trans('Global data was updated'));
return \Response::json( $response );
}
Route:
Route::post('admin/site-settings/global-data/update', ['as' => 'admin/global-data-update', 'uses' => 'admin\GlobalDatasController#updateGlobalData']);
Model:
class GlobalData extends Model
{
protected $fillable = ['company_name', 'address', 'city', 'zip', 'country', 'cvr', 'email', 'phone', 'logo' ];
}
Ajax:
function update () {
var url = '{{route('admin/global-data-update')}}';
var part = '{{ $globalData->part }}';
var data = $("#update_form").serialize();
var jqxhr = $.post(url, {
data: data,
part: part
},
function() {
})
.done(function() {
var json_response = jqxhr.responseText;
if(json_response) {
load_data('{{route('admin/global-data-edit')}}', '{{ $globalData->part }}');
} else {
console.log("Error");
}
})
}
And my form:
{!! Form::model($globalData, ['id' => 'update_form']) !!}
<div class="form-group">
{!! Form::text('company_name', null, array('class' => 'form-control', 'placeholder' => trans('Company name'))) !!}
</div>
<div class="form-group">
{!! Form::text('address', null, array('class' => 'form-control', 'placeholder' => trans('Address'))) !!}
</div>
<div class="form-group">
{!! Form::text('city', null, array('class' => 'form-control', 'placeholder' => trans('city'))) !!}
</div>
<div class="form-group">
{!! Form::text('zip', null, array('class' => 'form-control', 'placeholder' => trans('zip'))) !!}
</div>
<div class="form-group">
{!! Form::text('country', null, array('class' => 'form-control', 'placeholder' => trans('country'))) !!}
</div>
<div class="form-group">
{!! Form::text('cvr', null, array('class' => 'form-control', 'placeholder' => trans('cvr'))) !!}
</div>
<div class="form-group">
{!! Form::text('email', null, array('class' => 'form-control', 'placeholder' => trans('email'))) !!}
</div>
<div class="form-group">
{!! Form::text('phone', null, array('class' => 'form-control', 'placeholder' => trans('phone'))) !!}
</div>
<div class="form-group">
{{ Form::hidden('id') }}
</div>
{!! Form::button(trans('Save changes'), ['class' => 'pull-right btn btn-success save', 'id' => 'save' ]) !!}
{!! Form::close() !!}
I really would love some help, thank you for your time! :-)

Mistake at address word
$validator = Validator::make($request->all(), [
'company_name' => 'required',
'adress' => 'required',
'city' => 'required',
'zip' => 'required',
'country' => 'required',
'cvr' => 'required',
'email' => 'required|email',
'phone' => 'required'
]);

Related

How can you properly create a form which has options to fill for text fields and an option to upload an image? PHP/Laravel

I have created a form which has fillable input fields but there is an option to upload an image to.
The form example:
{!! Form::open(['method' => 'POST', 'route' => ['app.json-ld.update']])!!}
{!! Form::label('name', 'Store name', ['class' => 'form-label']) !!}
{!! Form::text('name', $shop->jsonLDFields->name ?? '', ['class' => 'form-control']) !!}
{!! Form::label('url', 'Store url', ['class' => 'form-label']) !!}
{!! Form::text('url', $shop->jsonLDFields->url ?? '', ['class' => 'form-control']) !!}
{!! Form::label('description', 'Store Description', ['class' => 'form-label']) !!}
{!! Form::textarea('description', $shop->jsonLDFields->description ?? '', ['class' => 'form-
control form-textarea']) !!}
{!! Form::label('telephone', 'Phone number', ['class' => 'form-label']) !!}
{!! Form::text('telephone', $shop->jsonLDFields->telephone ?? '', ['class' => 'form-
control']) !!}
{!! Form::label('image', 'Upload store image', ['class' => 'form-label']) !!}
{!! Form::file('image', (['class' => 'my-1'])) !!}
<button class="btn btn-success my-2" type="submit">Update</button>
{!! Form::close() !!}
Controller:
public function update(Request $request)
{
$shop = Shop::with('jsonLDFields')->first();
$shop->jsonLDFields->update([
'name' => $request->name,
'url' => $request->url,
'description' => $request->description,
'telephone' => $request->telephone
]);
return back();
I have another controller method which works for uploading, but I don't want to make multiple forms
public function uploadImage(Request $request)
{
$shop = Shop::with('jsonLDFields')->first();
$jsonLd = $shop->jsonLDFields;
if(!$jsonLd) return back();
$request->validate(['image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048']);
$image = $request->image;
$filename = Str::slug(microtime()) . '.' . $image->getClientOriginalExtension();
$request->image->move(public_path('images/json-ld/images'), $filename);
$jsonLd->image = $filename;
$jsonLd->save();
return back();
}
How can I implement an option to upload an image file in update controller method?
Have been trying in different ways, but the result was null.
Would appreciate help with a solution.
Just test if the request input image has file: if($request->hasFile('image')) and if so, than make same steps as in uploadImage()
public function update(Request $request)
$shop = Shop::with('jsonLDFields')->first();
$updateArray = [
'name' => $request->name,
'url' => $request->url,
'description' => $request->description,
'telephone' => $request->telephone
];
if($request->hasFile('image')){
$image = $request->image;
$filename = Str::slug(microtime()) . '.' . $image->getClientOriginalExtension();
$request->image->move(public_path('images/json-ld/images'), $filename);
$updateArray['image'] = $filename;
}
$shop->jsonLDFields->update($updateArray);
return back();
}
Of course, you should also implement validator ... But for simple example, this should be working.

Laravel validation doesn't validate html entities

I'm working with Laravel 5.5 and I'm trying to make validation of a form which shouldn't pass if user write html entities, for example: <h1>Hola</h1>, <script>alert(1)</script>.
But it insert all field in DB.
My controller:
protected function storeForm(CaseRequest $request){
try {
$supportCase = new SupportCase;
$supportCase->type = $request->input('type');
// all fields of table[...]
$supportCase->save();
return view('steps/finish/success')->with(['message' => 'Form success']);
} catch (Exception $e) {
echo $e->getMessage();
return view('steps/finish/error')->withErrors(['message' => 'Form error']);
}
}
My CaseRequest is this:
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'type' => 'required|min:3|max:3|string',
'brand' => 'required|string',
'product' => 'required|string',
'order' => 'required|string',
'description' => 'required|min:10|string',
'sn' => 'nullable',
'name' => 'required|min:2|string',
'nin' => 'required|min:9|max:11|alpha_dash',
'email' => 'required|email',
'phone' => 'required|digits_between:7,12',
'address' => 'required|min:5|string',
'city' => 'required|min:2|string',
'zip' => 'required|min:2|numeric',
'state' => 'required|min:2|string',
'country' => 'required|min:2|string',
];
}
I have read the documentation and the Request is the first to be called, before than controller, and if this has any error it throw a error message. Doesn't it?.
I'm using parsley and select2, at first it has a validation in frontend with parley, and it's working well, but if I remove parsley validation now Laravel should validate it, right? but in my DB it is saving all fields (included<script>alert(1)</script>).
<div class="form" id="main-form" data-parsley-validate="data-parsley-validate">
{!! Form::open(['id' => 'main-form', 'data-parsley-validate' => 'data-parsley-validate']) !!}
<div class="col-md-7 light-form">
<fieldset>
{!! Form::label('contact', trans('frontend/steps.form.contact'), ['class' => 'upper']) !!}
{!! Form::label('name', trans('frontend/steps.form.name')) !!}
{!! Form::text('name', old('name'), [
'data-parsley-pattern' => '[ÁÉÍÓÚáéíóúa-zA-Z ]+$',
'data-parsley-required' => 'true',
'data-parsley-minlength'=>'2',
'data-parsley-required-message' => trans('frontend/steps.form-errors.name'),
'data-parsley-minlength-message' => trans('frontend/steps.form-errors.name'),
'data-parsley-pattern-message' => trans('frontend/steps.form-errors.name'),
]) !!}
</fieldset>
<fieldset>
{!! Form::label('nin', trans('frontend/steps.form.in')) !!}
{!! Form::text('nin', old('nin'), [
'data-parsley-type'=>'alphanum',
'data-parsley-required' => 'true',
'data-parsley-minlength'=>'9',
'data-parsley-maxlength'=>'11',
'data-parsley-required-message' => trans('frontend/steps.form-errors.in'),
'data-parsley-minlength-message' => trans('frontend/steps.form-errors.in'),
'data-parsley-maxlength-message' => trans('frontend/steps.form-errors.in')
]) !!}
</fieldset>
<fieldset>
{!! Form::label('phone', trans('frontend/steps.form.telf')) !!}
{!! Form::text('phone', old('phone'), [
'data-parsley-pattern' => '\d+$',
'data-parsley-required' => 'true',
'data-parsley-minlength'=>'7',
'data-parsley-maxlength'=>'12',
'data-parsley-required-message' => trans('frontend/steps.form-errors.telf'),
'data-parsley-minlength-message' => trans('frontend/steps.form-errors.telf'),
'data-parsley-maxlength-message' => trans('frontend/steps.form-errors.telf'),
'data-parsley-pattern-message' => trans('frontend/steps.form-errors.telf')
]) !!}
</fieldset>
<fieldset>
{!! Form::label('address', trans('frontend/steps.form.address')) !!}
{!! Form::text('address', old('address'), [
'data-parsley-pattern' => '^[ÁÉÍÓÚáéíóúa-zA-Z0-9-_ ]+$',
'data-parsley-required' => 'true',
'data-parsley-minlength'=>'5',
'data-parsley-pattern-message' => trans('frontend/steps.form-errors.address'),
'data-parsley-minlength-message' => trans('frontend/steps.form-errors.address'),
'data-parsley-required-message' => trans('frontend/steps.form-errors.address'),
]) !!}
</fieldset>
<div class="col-md-12 no-padding">
<div class="col-md-6 location-form">
<fieldset>
{!! Form::label('address', trans('frontend/steps.form.city')) !!}
{!! Form::text('city', old('city'), [
'data-parsley-required' => 'true',
'data-parsley-minlength'=>'2',
'data-parsley-pattern' => '[ÁÉÍÓÚáéíóúa-zA-Z ]+$',
'data-parsley-minlength-message' => trans('frontend/steps.form-errors.city'),
'data-parsley-required-message' => trans('frontend/steps.form-errors.city'),
'data-parsley-pattern-message' => trans('frontend/steps.form-errors.city'),
]) !!}
</fieldset>
<fieldset>
{!! Form::label('zip', trans('frontend/steps.form.zip')) !!}
{!! Form::text('zip', old('zip'), [
'data-parsley-required' => 'true',
'data-parsley-minlength'=>'2',
'data-parsley-minlength-message' => trans('frontend/steps.form-errors.zip'),
'data-parsley-required-message' => trans('frontend/steps.form-errors.zip')
]) !!}
</fieldset>
</div>
<div class="col-md-6 no-padding">
<fieldset>
{!! Form::label('state', trans('frontend/steps.form.state')) !!}
{!! Form::text('state', old('state'), [
'data-parsley-pattern' => '[ÁÉÍÓÚáéíóúa-zA-Z ]+$',
'data-parsley-required' => 'true',
'data-parsley-minlength'=>'2',
'data-parsley-required-message' => trans('frontend/steps.form-errors.state'),
'data-parsley-minlength-message' => trans('frontend/steps.form-errors.state'),
'data-parsley-pattern-message' => trans('frontend/steps.form-errors.state'),
]) !!}
</fieldset>
<fieldset>
{!! Form::label('country', trans('frontend/steps.form.country')) !!}
{!! Form::text('country', old('country'), [
'data-parsley-required' => 'true',
'data-parsley-pattern' => '[ÁÉÍÓÚáéíóúa-zA-Z ]+$',
'data-parsley-minlength'=>'2',
'data-parsley-required-message' => trans('frontend/steps.form-errors.country'),
'data-parsley-minlength-message' => trans('frontend/steps.form-errors.country'),
'data-parsley-pattern-message' => trans('frontend/steps.form-errors.country'),
]) !!}
</fieldset>
</div>
</div>
</div>
<div class="col-md-5 dark-form">
<fieldset>
{!! Form::label('order', trans('frontend/steps.form.order'), ['class' => 'upper']) !!}
{!! Form::text('order', old('order'), [
'placeholder' => '123567',
'data-parsley-type' => 'digits',
'data-parsley-type-message' => trans('frontend/steps.form-errors.order_format'),
'data-parsley-required' => 'true',
'data-parsley-required-message' => trans('frontend/steps.form-errors.order')
]) !!}
<span class="loading style-2"></span>
</fieldset>
<fieldset id="brand-wrap">
<label class="upper" for="brand">
{!! trans('frontend/steps.form.brand') !!}
<img class="tip" title="{!! trans('frontend/steps.form.brand_tooltip') !!}"
src="{!! asset('assets/img/frontend/icons/info.png') !!}"/>
</label>
{!! Form::select('brand', $layout->brands->pluck('name', 'id'), old('brand'), [
'id'=> 'brand',
'class' => 'select2',
'data-parsley-required' => 'true',
'data-parsley-required-message' => trans('frontend/steps.form-errors.brand')
])
!!}
<span class="loading style-2"></span>
</fieldset>
<fieldset id="product-wrap">
{!! Form::label('product', trans('frontend/steps.form.product'), ['class' => 'upper']) !!}
{!! Form::select('product', ['null' => 'null'], old('product'), [
'id'=> 'product_select',
'class' => 'select2',
'data-parsley-required' => 'true',
'data-parsley-required-message' => trans('frontend/steps.form-errors.product')
])
!!}
</fieldset>
<fieldset>
{!! Form::label('description', trans('frontend/steps.form.problem'), ['class' => 'upper']) !!}
{!! Form::textarea('description', old('description'), [
'data-parsley-pattern' => '[áéíóúÁÉÍÓÚäëïöüÄËÏÖÜa-zA-Z0-9-_ ]+$',
'data-parsley-minlength'=>'10',
'data-parsley-required' => 'true',
'data-parsley-type-message' => trans('frontend/steps.form-errors.problem'),
'data-parsley-required-message' => trans('frontend/steps.form-errors.problem'),
'data-parsley-minlength-message' => trans('frontend/steps.form-errors.problem'),
'data-parsley-pattern-message' => trans('frontend/steps.form-errors.problem')
]) !!}
</fieldset>
<fieldset id="serial-wrap">
{!! Form::label('sn', trans('frontend/steps.form.serial')) !!}
{!! Form::text('sn', old('sn'), [
'id' => 'sn',
'data-parsley-required' => 'false',
'data-parsley-required-message' => trans('frontend/steps.form-errors.imei'),
'data-parsley-lunhvalidator' => '15',
'data-parsley-lunhvalidator-message' => trans('frontend/steps.form-errors.invalid-imei')
])
!!}
</fieldset>
<fieldset>
{!! Form::label('email', trans('frontend/steps.form.email')) !!}
{!! Form::email('email', old('email'), [
'data-parsley-type'=> 'email',
'data-parsley-required' => 'true',
'data-parsley-type-message' => trans('frontend/steps.form-errors.email'),
'data-parsley-required-message' => trans('frontend/steps.form-errors.email')
]) !!}
</fieldset>
#if($case == "INC")
<button class="upper" type="button" onclick="nextStep(this)" data-type="FORM" data-field="transaction"
data-next="eleventh" data-case="{!! $case !!}"
data-value="">{!! trans('frontend/steps.form.continue') !!}</button>
#else
<button class="upper" type="button" onclick="nextStep(this)" data-type="FORM" data-field="transaction"
data-next="fifth" data-case="{!! $case !!}"
data-value="">{!! trans('frontend/steps.form.continue') !!}</button>
#endif
</div>
{!! Form::close() !!}
</div>
Validation doesn't change input data. It just ensures the input matches your defined rules.
Technically there is no need to remove HTML tags. They won't do any harm in the database and can be escaped when outputting with {{ $content }}.
If you don't want to save HTML in your database use strip_tags() on the relevant fields.
But don't rely on it to prevent XSS, escaping output is still necessary

Eloquent multiple option filter

I have a search form to filter Multiple options from Multiple select boxes to filter out revenues. Here I have a 'Accounts" filter which I have (working right now) All accounts or a single account filter. What I need is to be able to Filter All, Single or multiple accounts based on user selection.
My Form:
{!! Form::open(['url' => 'incomes/revenues', 'role' => 'form', 'method' => 'GET']) !!}
<div class="pull-left">
<span class="title-filter hidden-xs">{{ trans('general.search') }}:</span>
<!--{!! Form::text('search', request('search'), ['class' => 'form-control input-filter input-sm', 'placeholder' => trans('general.search_placeholder')]) !!}-->
{!! Form::text('start', request('start'), ['class' => 'form-control input-filter input-sm','id' => 'datepicker', 'placeholder' => trans('general.date_placeholder')]) !!}
{!! Form::text('end', request('end'), ['class' => 'form-control input-filter input-sm','id' => 'datepicker1', 'placeholder' => trans('general.date_placeholder')]) !!}
{!! Form::select('customer', $customers, request('customer'), ['class' => 'form-control input-filter input-sm']) !!}
{!! Form::select('category', $categories, request('category'), ['class' => 'form-control input-filter input-sm']) !!}
{!! Form::select('account', $accounts, request('account'), ['multiple' => 'true','class' => 'form-control input-filter input-sm']) !!}
{!! Form::button('<span class="fa fa-filter"></span> ' . trans('general.filter'), ['type' => 'submit', 'class' => 'btn btn-sm btn-default btn-filter']) !!}
</div>
My Controller
public function index()
{
$revenues = Revenue::with(['account', 'category', 'customer'])->isNotTransfer()->collect(['paid_at'=> 'desc']);
$customers = collect(Customer::enabled()->pluck('name', 'id'))
->prepend(trans('general.all_type', ['type' => trans_choice('general.customers', 2)]), '');
$categories = collect(Category::enabled()->type('income')->pluck('name', 'id'))
->prepend(trans('general.all_type', ['type' => trans_choice('general.categories', 2)]), '');
$accounts = collect(Account::enabled()->pluck('name', 'id')->toArray())
->prepend(trans('general.all_type', ['type' => trans_choice('general.accounts', 2)]), '');
$transfer_cat_id = Category::transfer();
return view('incomes.revenues.index', compact('revenues', 'customers', 'categories', 'accounts', 'transfer_cat_id'));
}
My Filter
public $relations = [];
public function search($query)
{
return $this->whereLike('description', $query);
}
public function start($start)
{
return $this->where('paid_at','>=' , $start);
}
public function end($end)
{
return $this->where('paid_at','<=' , $end);
}
public function customer($customer)
{
return $this->where('customer_id', $customer);
}
public function category($category)
{
return $this->where('category_id', $category);
}
public function account($account)
{
return $this->where('account_id', $account);
}
}
Will be grateful if any one can show me how to achieve this. Thanks.

Multi option filter from selection in laravel

I have a search form to filter out accounts to show their transactions using relations. I have it working to filter a single account. I need to create the filter multiple accounts together. Here is my code for filtering a single selection since I am ne to Laravel< I am getting stuck. Thanks in advance.
public $relations = [];
public function account($account)
{
return $this->where('account_id', $account);
} }
This is my form:-
{!! Form::open(['url' => 'incomes/revenues', 'role' => 'form', 'method' => 'GET']) !!}
<div class="pull-left">
<span class="title-filter hidden-xs">{{ trans('general.search') }}:</span>
<!--{!! Form::text('search', request('search'), ['class' => 'form-control input-filter input-sm', 'placeholder' => trans('general.search_placeholder')]) !!}-->
{!! Form::text('start', request('start'), ['class' => 'form-control input-filter input-sm', 'placeholder' => trans('general.date_placeholder')]) !!}
{!! Form::text('end', request('end'), ['class' => 'form-control input-filter input-sm', 'placeholder' => trans('general.date_placeholder')]) !!}
{!! Form::select('customer', $customers, request('customer'), ['class' => 'form-control input-filter input-sm']) !!}
{!! Form::select('category', $categories, request('category'), ['class' => 'form-control input-filter input-sm']) !!}
{!! Form::select('account', $accounts, request('account'), ['multiple' => 'true','class' => 'form-control input-filter input-sm']) !!}
{!! Form::button('<span class="fa fa-filter"></span> ' . trans('general.filter'), ['type' => 'submit', 'class' => 'btn btn-sm btn-default btn-filter']) !!}
controller
public function index()
{
$revenues = Revenue::with(['account', 'category', 'customer'])->isNotTransfer()->collect(['paid_at'=> 'desc']);
$customers = collect(Customer::enabled()->pluck('name', 'id'))
->prepend(trans('general.all_type', ['type' => trans_choice('general.customers', 2)]), '');
$categories = collect(Category::enabled()->type('income')->pluck('name', 'id'))
->prepend(trans('general.all_type', ['type' => trans_choice('general.categories', 2)]), '');
$accounts = collect(Account::enabled()->pluck('name', 'id'))
->prepend(trans('general.all_type', ['type' => trans_choice('general.accounts', 2)]), '');
$transfer_cat_id = Category::transfer();
return view('incomes.revenues.index', compact('revenues', 'customers', 'categories', 'accounts', 'transfer_cat_id'));
}

Stripe.js and Laravel - Token not generated by Javascript or passed to server

Query regarding stripe.js token. :)
I have a basic checkout set up. I'm using Laravel and Stripe.js to process payments. I have followed a guide but seem to be having trouble getting Stripe.js to generate and pass a token to the server.
Laravel Payment Form (validated with Parsley.js):
{!! Form::open(['url' => '/order/'.$order_info['script_id'].'/post', 'data-parsley-validate','id' => 'payment-form']) !!}
<div class="form-group" id="first-name-group">
{!! Form::label('firstName', 'First Name:') !!}
{!! Form::text('first_name', null, [
'class' => 'form-control',
'required' => 'required',
'data-parsley-required-message' => 'First name is required',
'data-parsley-trigger' => 'change focusout',
'data-parsley-pattern' => '/^[a-zA-Z]*$/',
'data-parsley-minlength' => '2',
'data-parsley-maxlength' => '32',
'data-parsley-class-handler' => '#first-name-group'
]) !!}
</div>
<div class="form-group" id="last-name-group">
{!! Form::label('lastName', 'Last Name:') !!}
{!! Form::text('last_name', null, [
'class' => 'form-control',
'required' => 'required',
'data-parsley-required-message' => 'Last name is required',
'data-parsley-trigger' => 'change focusout',
'data-parsley-pattern' => '/^[a-zA-Z]*$/',
'data-parsley-minlength' => '2',
'data-parsley-maxlength' => '32',
'data-parsley-class-handler' => '#last-name-group'
]) !!}
</div>
<div class="form-group" id="email-group">
{!! Form::label('email', 'Email address:') !!}
{!! Form::email('email', null, [
'class' => 'form-control',
'placeholder' => 'email#example.com',
'required' => 'required',
'data-parsley-required-message' => 'Email name is required',
'data-parsley-trigger' => 'change focusout',
'data-parsley-class-handler' => '#email-group'
]) !!}
</div>
<div class="form-group" id="cc-group">
{!! Form::label(null, 'Credit card number:') !!}
{!! Form::text(null, null, [
'class' => 'form-control ',
'id' => 'card-number',
'required' => 'required',
'data-parsley-type' => 'number',
'maxlength' => '16',
'data-parsley-trigger' => 'change focusout',
'data-parsley-class-handler' => '#cc-group'
]) !!}
</div>
<div class="form-group" id="ccv-group">
{!! Form::label(null, 'Card Validation Code (3 or 4 digit number):') !!}
{!! Form::text(null, null, [
'class' => 'form-control',
'id' => 'card-cvc',
'required' => 'required',
'data-parsley-type' => 'number',
'data-parsley-trigger' => 'change focusout',
'maxlength' => '4',
'data-parsley-class-handler' => '#ccv-group'
]) !!}
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group" id="exp-m-group">
{!! Form::label(null, 'Ex. Month') !!}
{!! Form::selectMonth(null, null, [
'class' => 'form-control',
'id' => 'card-expiry-month',
'required' => 'required'
], '%m') !!}
</div>
</div>
<div class="col-md-4">
<div class="form-group" id="exp-y-group">
{!! Form::label(null, 'Ex. Year') !!}
{!! Form::selectYear(null, date('Y'), date('Y') + 10, null, [
'class' => 'form-control',
'id' => 'card-expiry-year',
'required' => 'required'
]) !!}
</div>
</div>
</div>
<div class="form-group">
{!! Form::submit('Place order!', ['class' => 'btn btn-primary btn-order', 'id' => 'submitBtn', 'style' => 'margin-bottom: 10px;']) !!}
</div>
<div class="row">
<div class="col-md-12">
<span class="payment-errors" style="color: red;margin-top:10px;"></span>
</div>
</div>
{!! Form::close() !!}
JS:
<!-- Inlude Stripe.js -->
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script>
// This identifies your website in the createToken call below
Stripe.setPublishableKey('{!! env('STRIPE_PK') !!}');
jQuery(function($) {
$('#payment-form').submit(function(event) {
var $form = $(this);
// Before passing data to Stripe, trigger Parsley Client side validation
$form.parsley().subscribe('parsley:form:validate', function(formInstance) {
formInstance.submitEvent.preventDefault();
return false;
});
// Disable the submit button to prevent repeated clicks
$form.find('#submitBtn').prop('disabled', true);
Stripe.card.createToken({
number: $('#card-number').val(),
cvc: $('#card-cvc').val(),
exp_month: $('#card-expiry-month').val(),
exp_year: $('#card-expiry-year').val()
}, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
function stripeResponseHandler(status, response) {
console.log(token); //outputs "undefined" to console
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('.payment-errors').addClass('alert alert-danger');
$form.find('#submitBtn').prop('disabled', false);
$('#submitBtn').button('reset');
} else {
// response contains id and card, which contains additional card details
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
// and submit
$form.get(0).submit();
}
};
</script>
Controller Action:
public function postOrder(Request $request, $script_id){
$validator = \Validator::make(\Input::all(), [
'first_name' => 'required|string|min:2|max:32',
'last_name' => 'required|string|min:2|max:32',
'email' => 'required|email',
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator);
}
$token = $request->input('stripeToken');
//dd($token);
$first_name = $request->input('first_name');
$last_name = $request->input('last_name');
$email = $request->input('email');
$price = $request->input['price'];
$emailCheck = User::where('email', $email)->value('email');
//dd($emailCheck);
\Stripe\Stripe::setApiKey(env('STRIPE_SK'));
// If the email doesn't exist in the database create new customer and user record
if (!isset($emailCheck)) {
// Create a new Stripe customer
try {
$customer = \Stripe\Customer::create([
'source' => $token,
'email' => $email,
'metadata' => [
"First Name" => $first_name,
"Last Name" => $last_name
]
]);
} catch (\Stripe\Error\Card $e) {
return "fail";
}
}
// dd(Auth::user()->stripe_customer_id);
if(Auth::user()->stripe_customer_id == ""){
$user = Auth::user();
$user->stripe_customer_id = $customer->id;
$user->save();
$customerID = $customer->id;
}
else{
$customerID = Auth::user()->stripe_customer_id;
}
// charge customer
// dd($customerID);
try {
$charge = \Stripe\Charge::create([
'amount' => $price,
'currency' => 'usd',
'customer' => $customerID,
'metadata' => [
'product_name' => "Vidmaker Purchase"
]
]);
} catch (\Stripe\Error\Card $e) {
/* return redirect()->route('order')
->withErrors($e->getMessage())
->withInput();*/
dd($e->getMessage());
}
Order::create([
'user_id' => $user->id,
'script_id' => $script_id,
'amount' => $price,
'stripe_transaction_id' => $charge->id,
]);
/*return redirect()->route('order')
->with('successful', 'Your purchase was successful!');*/
return "Success";
}
}
When I try use "stripeToken" on the server it is null - I checked it and it's not being passed in the POST method.
I've been tinkering with the JS for hours. I even have the card details printing out to the console find. But when passed into Stripe.card.createToken() no token is generated.
It proceeds to the server anyways and the Stripe::charge() action catches an error saying :
"Cannot charge a customer that has no active card"
Anyone have any idea? I've spend a good six hours and at this point I'm truly stumped.
Cheers,
Dean

Categories