In my Laravel 5.6 application, I try to pass a $id
variable from my route to each single column of my datatable.
My code:
public function getVendorslistChange($id){
try {
return Datatables::of($this->purchaseRepository->getVendorListData(),$id)
->addColumn('action', function ($vendor,$id) {
return \Form::open(['method' => 'POST', 'action' => ['PurchaseController@postChangeVendor',$id], 'class' => 'form']) . '
<input type="hidden" name="id" value="' . $vendor->id . '" />
<input type="submit" name="submit" value="Choose" class="btn center-block" />
' . \Form::close();
})
->make(true);
} catch (\Exception $e) {
return $this->redirectWithErrors($e);
}
}
this part $this->purchaseRepository->getVendorListData()
will return the following:
public function getVendorListData(){
$this->vendors = Vendor::Select(
array(
'vendors.id',
'vendors.company_name'
))
->where('vendors.company_id',return_company_id())
->where('status','Active')->get()
;
return $this->vendors;
}
But there is error said, the $id
cannot be passed to the addColumn
.
Too few arguments to function App\Http\Controllers\PurchaseController::App\Http\Controllers{closure}(), 1 passed in /Applications/XAMPP/xamppfiles/htdocs/laravel-project/american_dunnage/vendor/yajra/laravel-datatables-oracle/src/Utilities/Helper.php on line 64 and exactly 2 expected
What is the proper way to pass parameter like this to each column of the datatable?
You shouldn't just add parameters to vendor functions if they don't support them. For example, when you call Datatables::of()
, the source code shows that it only expects one parameter. So even though you pass the extra $id
variable, that $id
won't be passed to the callback function that you give to addColumn()
. That's why you see that error about too few arguments being passed in.
https://github.com/yajra/laravel-datatables/blob/8.0/src/DataTables.php#L33
Something like this might work. Notice how I'm telling the callback to use
the $id
instead of trying to pass it directly into the function call:
public function getVendorslistChange($id){
try {
return Datatables::of($this->purchaseRepository->getVendorListData())
->addColumn('action', function ($vendor) use ($id) {
return \Form::open(['method' => 'POST', 'action' => ['PurchaseController@postChangeVendor',$id], 'class' => 'form']) . '
<input type="hidden" name="id" value="' . $vendor->id . '" />
<input type="submit" name="submit" value="Choose" class="btn center-block" />
' . \Form::close();
})
->make(true);
} catch (\Exception $e) {
return $this->redirectWithErrors($e);
}
}
Check out example 3 in the docs to see how to manage anonymous function scopes:
http://php.net/manual/en/functions.anonymous.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With