I have a route that must get some parameters:
Route::get('users/{function}/{param}/{feeLimit}/{callValue}/{bandwidthLimit}' , [TronController::class, 'totalUsers']);
And the method totalUsers looks like this:
public function totalUsers($function,$params,$feeLimit,$callValue,$bandwidthLimit){
And in the browser, I call it like this:
http://localhost:8000/users/totalUsers/array()/30000000/0/0
But now I get this error:
Function params must be an array
I know this way of adding parameters is wrong, but I don't how to call the url and variables like this on the browser:
$function="totalUsers";
$params=array();
$feeLimit=30000000;
$callValue = 0;
$bandwidthLimit = 0;
How can I call totalUsers method properly with its parameters?
Update 1
In the method totalUsers:
try {
$trigger = $TransactionBuilder->triggerSmartContract(
(array)$abi,
$contractH,
$function,
$params,
$feeLimit,
$addressH,
$callValue = 0,
$bandwidthLimit = 0);
var_dump($trigger);
} catch (\IEXBase\TronAPI\Exception\TronException $e) {
die($e->getMessage());
}
Easily You can solve this problem by using this route as post:
Route::post('/users' , [TronController::class, 'totalUsers'])->name('users');
Then you can send the value by submitting a form:
<form action="{{ route('users') }}" method="post">
#csrf
<input type="text" name="function" />
<input type="text" name="params[]" />
<input type="text" name="params[]" />
<input type="text" name="params[]" />
.... // how much you want
<input type="text" name="feeLimit" />
<input type="text" name="callValue" />
<input type="text" name="bandwidthLimit" />
<input type="submit" value="Send">
</form>
You will be getting an array for this params field, this is secure and you can send a large number of data character:
In the controller:
public function totalUsers(Request $request)
{
$function=$request->function;
$params=$request->param; // this will be an array
$feeLimit=$request->feeLimit;
$callValue = $request->callValue;
$bandwidthLimit = $request->bandwidthLimit;
foreach( $params as $param )
{
$param; // do what ever you want
}
}
Your error has nothing to do with routes, it's a tron-api's error. The triggerSmartContract() function expects $params to be an array, but you're passing a string.
Easy way to solve that would be just convert your $params string to array in the arguments (array)$params.
Correct way would be to follow advice in this answer, though I'd suggest to validate user input:
public function totalUsers(Request $request)
{
$request->validate([
'function' => 'required|string',
'params' => 'required|array',
'feeLimit' => 'required|numeric',
'callValue' => 'sometimes|numeric',
'bandwidthLimit' => 'sometimes|numeric',
]);
try {
$trigger = $TransactionBuilder->triggerSmartContract(
(array)$abi,
$contractH,
$request->input('function'),
$request->input('params'),
$request->input('feeLimit'),
$addressH,
$request->input('callValue', 0),
$request->input('bandwidthLimit', 0)
);
var_dump($trigger);
} catch (\IEXBase\TronAPI\Exception\TronException $e) {
die($e->getMessage());
}
}
Related
Before looking for a page I wanted to check if the id exists, so if I don't find it, give up looking I tried as follows:
My controller product
public function search(Request $request)
{
$id = $request->input('id');
if($produto = Produto::find($id)) {
return view('produtos.show', compact('produto', 'id'));
}
// $search_results=Produto::findOrFail($id);
return 'Not found';
}
->My Route->
Route::get('/produtos/editar/{id?}','App\Http\Controllers\ProdutosController#search')->name('searchproduct');
->My Blade Form
<form id="search" method="GET" action="{{ route('searchproduct') }}" >
<input id="q" name="q" type="text" /></br>
<button type="submit" id="submitButton" >Alterar</button>
</form>
</div>
</div>
</div>
</div>
->My Jquery Script
jQuery(document).ready(function(){
jQuery("form#search").on('submit',function(e){
e.preventDefault();
var q = jQuery("#q").val();
window.location.href = jQuery(this).prop('action')+"/" + encodeURIComponent(q)
});
});
How can i check in database before? send It's always going to the default 404 page
It's enough to check $search_results variable. I changed findOrFail with find because findOrFail may throw an error.
public function search(Request $request) {
$search_results = Produto::find($request->input('id'));
if ($search_results == NULL) {
abort(404);
}
return view('produtos.show', ['produto' => $search_results, 'id' => $request->input('id')]);
}
Also yo can use:
public function search(Request $request) {
$search_results = Produto::where('id', '=', $request->input('id'))->first();
if ($search_results == NULL) {
abort(404);
}
return view('produtos.show', ['produto' => $search_results, 'id' => $request->input('id')]);
}
Two ways to go about it:
exists:
if (Produto::where('id', $id)->exists()) {
$search_results=Produto::find($id);
}
findOr:
$search_results = Produto::findOr($id, function () {
// whatever you want to do if no record is found
});
to show a 404 page use this code :
public function search(Request $request)
{
//if not found it will trigger 404 not found page
$produto = Produto::findOrFail($id = $request->input('id'));
//otherwise it will return the view of produtos.show
return view('produtos.show', compact('produto', 'id'));
}
or you can use this code too to use a custom return
public function search(Request $request)
{
$id = $request->input('id');
if($produto = Produto::find($id)) {
return view('produtos.show', compact('produto', 'id'));
}
//otherwise return your error view or message
return 'Not found';
}
-> your route must be get not post
Route::get('/produtos/editar/{id?}','ProdutosController#search')->name('searchproduct');
-> no need for #csrf for get method
<form id="search" method="GET" action="{{ route('searchproduct') }}" >
<input id="q" type="text" /></br>
<button type="submit" id="submitButton" >Alterar</button>
</form>
In Slim framework 4; How can I return a Formr-form in my controller as a response to a get-request?
$app->group('/timer', function (Group $group) {
$group->get('/', function (Request $request, Response $response) {
$form = new Formr\Formr();
// $form->create_form('Name')
// die();
$response->getBody()->write($form->create_form('Name'));
return $response;
});
});
The code outputs nothing. However, if I uncomment the two lines, it outputs (as expected):
<form action="/index.php" id="myFormr" method="post" accept-charset="utf-8">
<input type="hidden" name="FormrID" value="myFormr"><label for="name">Name</label>
<input type="text" name="name" id="name" />
<button type="submit" name="button" id="button">Submit</button>
</form>
From Formr documentations:
Formr will automatically echo form elements and messages to the
screen, and this is usually fine. However, in some instances - such as
when using a templating framework - this is not an option. In these
cases simply pass the word hush and then manually echo your elements
and messages.
$form = new Formr\Formr('bootstrap', 'hush');
The default value for the first parameter of Formr\Formr constructor is an empty string, so in your case you should create new Formr instance with an empty string '' as the first parameter ann 'hush' as the second parameter:
$app->group('/timer', function (Group $group) {
$group->get('/', function (Request $request, Response $response) {
// required change
$form = new Formr\Formr('', 'hush');
$response->getBody()->write($form->create_form('Name'));
return $response;
});
});
I'm having trouble doing a record update array via POST in Laravel.
I have captured all the post data in an array cant update array achievement
<form action="{{'updateapp'}}" method="post">
<table>
<tr><td>
<input type="checkbox" class="id" name="id[]" value="{{ $quarter->id }}" />
<input type="text" name="achv[]" value="{{ $quarter->achievement }}">
</td></tr>
</table>
</form>
Controller :
public function foo(Request $request)
{
$ids = $request->id;
$achvs = $request->achv;
DB::table('quarters')->whereIn('id', $ids)
->update(array(['achievement' => $achvs ]));
return redirect('evaluator');
}
As you have set [] array in your form, you can access it as following
public function foo(Request $request)
{
$ids = $request->id[0];
$achvs = $request->achv[0];
DB::table('quarters')->where('id', $ids)
->update(['achievement' => $achvs ]);
return redirect('evaluator');
}
if you want to update multiple rows then use following code:
foreach($request->id as $key => $value){
$quarters = Quarters::find($request->id[$key]);
$quarters->achievement = $request->achv[$key];
$quarters->save();
}
public function foo(Request $request)
{
$ids = $request->id[0];
$achvs = $request->achv[0];
DB::table('quarters')->where('id', $ids)
->update(array(['achievement' => $achvs,'achievement1' => $achvs1]));
return redirect('evaluator');
}
I'm using OctoberCMS based on Laravel and Twig.
I have a form with checkboxes queued[]. They are submitted and deleted with Laravel using a loop.
It all works but how can I validate and sanitize the array?
Validate requires an asterisk *? '*' => Input::get('queued')?
Sanitize, I get the error trim() expects parameter 1 to be string, array given.
Form
<form method="POST" action="{{ url_current() }}">
<input type="hidden" name="_handler" value="onDelete" />
<input type="checkbox" name="queued[]" value="item1" />
<input type="checkbox" name="queued[]" value="item2" />
<input type="checkbox" name="queued[]" value="item3" />
<button type="submit" name="submit" value="delete">Delete Checked</button>
</form>
PHP
public function onDelete() {
# Validator
$validator = Validator::make(
[
'_handler' => Input::get('_handler'),
'queued' => Input::get('queued'),
'submit' => Input::get('submit')
]
);
if ($validator->fails()) {
return Redirect::back()->withErrors($validator);
exit();
}
# Sanitize
function sanitize_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = strip_tags($data);
$data = htmlspecialchars($data);
return $data;
}
# Delete Checked
$checkboxes = '';
$checkboxes = isset($_POST['queued']) ? $_POST['queued'] : array();
// Sanitize
$checkboxes = $this->sanitize_input($checkboxes);
foreach($checkboxes as $file) {
File::delete("$file");
}
}
You can write your own custom validation rules.
You can define a new rule in the plugins boot() method like this:
Validator::extend('myCustomRule', function($attribute, $value, $parameters) {
# check if the $value is in valid
# return true if it is and return false if it is not valid
return true;
});
You can foreach the array and then check the values. Depends on you validation rules, you might not need to sanitize after that.
And then you can use the custom rule by the name you supplied:
$validator = Validator::make(input(), [
'queued' => 'myCustomRule',
]
);
I'm having problem saving data to the database since catch exception is always being called. try always get ignored. I don't really know what's happening. I've been working for this for hours and I can't get it to work. I'm using kohana 3.3 and kostache.
So here's the controller.
Controller
APPATH/classes/controller/album.php
public function action_create()
{
$view = Kostache_Layout::factory();
$layout = new View_Pages_Album_List();
$album = ORM::factory('Album_Information');
$album_name = $this->request->post('inputAlbum');
$artist = $this->request->post('inputArtist');
$album->Album_Name = $album_name;
$album->Artist = $artist;
try
{
$album->save();
HTTP::redirect('album');
}
catch(ORM_Validation_Exception $e)
{
$layout->errors = $e->errors('models');
}
}
$this->response->body($view->render($layout));
}
Templates
APPATH/templates/pages/album/list.mustache
<h3>Add A New Album</h3>
<form action="album/create" method="post">
<label for="inputAlbum">Album Name:</label>
<input id="inputAlbum" type="text" name="inputAlbum" /><br />
<label for"inputAlbum" class="error">{{#errors}}{{inputAlbum}}{{/errors}}</label>
<label for="inputArtist">Album Artist:</label>
<input id="inputArtist" type="text" name="inputArtist" /><br />
<label for="inputArtist" class="error">{{#errors}}{{inputArtist}}{{/errors}}</label>
<input type="submit" name="submit" value="Add" />
</form>
Model Rules
APPATH/classes/model/album/information.php
class Model_Album_Information extends ORM
{
protected $_primary_key = 'ID';
protected $_table_name = 'album_information';
public function rules()
{
return array(
'inputAlbum' => array(
array('not_empty'),
),
'inputArtist' => array(
array('not_empty'),
),
);
}
Messages
APPATH/messages/models/album.php
return array(
'inputAlbum' => array(
'not_empty' => ':You must provide Album Name',
),
'inputArtist' => array(
'not_empty' => ':You must provide Album Artist',
),
);
The errors are showing when there's no input on the input field when i hit on the submit button, no problem with that, but even there's an input the errors are still being shown. So catch is always being called. When i remove try and catch I can easily save data to the database but there's no validation.
Thank you and more power.
You expect the ORM class to magically know the value of $album->Album_Name came from a HTTP form input named inputAlbum. It won't.
Create rules for the Album_Name and Artist properties of the ORM object itself. Not the possible input method.
The Controller knows what data to pass to models. The Model is only concerned with the data it received. Not where it came from.