Change request input values from empty string to null in Laravel - database

In my controller I receive an Illuminate\Http\Request Request that contains some data with values equal to an empty string:
dd($request->input())
//output
array:5 [▼
"_token" => "K43q88mR5zQRqVPAuYX5IWtQ1khQ24JTsuxl8mz4"
"param1" => "1"
"param2" => "2"
"param3" => ""
"param4" => ""
]
(basically that happens when the user had made no selections in the create form BUT due to frontend restrictions see here, I am not able to change the form of the Request so that to exclude the empty string values from being sent to the server)
The request input data is used to attach a relationships to models. For example:
$book->authors()->attach($request->input('param1'));
The problem is that when the input value is equal to the empty string "" the above line throws a QueryException, since it tries to add a foreign key equal to "" to the pivot table.
On the other hand, I noticed that if the value is null instead of "", the attach() method is not executed and, thus, does not throws an Exception, neither updates the database, which is exactly the behavior I want, when the user made no selection in the input form.
My question is how can I change the request values from "" to null? My first thought was to make a helper function that iterates over the request input array and replace "" with null and use it in the controller BUT it does not seems like a good idea for me, because this would not prevent possible unwanted validation errors, when using Form Request Validation.
Any ideas please ???
Thank you in advance

NOTE: Laravel 5.4 now ships with this feature
https://laravel.com/docs/5.4/requests#input-trimming-and-normalization
For versions > 5.4 see answer below or just copy the official middlewares.
HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application.
Make a middleware and assign it to the routes or controller's methods you want it to take place.
Example:
class SanitizeMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
foreach ($request->input() as $key => $value) {
if (empty($value)) {
$request->request->set($key, null);
}
}
return $next($request);
}
}
Route::post('/users', function (Request $request) {
dd($request->input());
})->middleware(SanitizeMiddleware::class);

This being said you can solve your problem as follows:
Comment out or put this in middleware in the
App\Http\Kernel.php file.
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];

Can't you just check before you add an item to your pivot table?
if(!empty($request->input('paramX'))){
$book->authors()->attach($request->input('paramX'));
}

Related

cakephp: Use save method , I want to update modified time when data no changed

Please help me solve this problem , thank you very much.
part 1 : data was changed , i use [ $this->abcModel->save($abc);], the abcTable's modified column was changed . ===> that is OK.
Part2 : data was no changed, i also want abcTable's modified column was changed,
How to do deal with ?
(if show me an example, will be more better to understand.)
using version: cakephp 3.3
Cakephp version : cakephp 3.3
$this->Model->touch($data);
[Rf.]
https://book.cakephp.org/3.0/en/orm/behaviors/timestamp.html
Let's Assume that you have a form with following fields.
Name: XYZ
Number :077777777
**save** button.
It has form action edit/update
Case 1: User make changes and save the form.
Case 2: User do not make any changes and saves the form.
In either case, you should call your controller edit(or update) function.
your NAME AND NUMBER fields will be available in your controller and can be accessed via
$this->request->getData() method.
Ideally, you will need two fields for timestamps as below:
'CREATED_ON' and 'UPDATED_ON'
you can use touch method as you mention but in an ideal world it will be better to write a behaviour to your model. it will update timestamp every time you create a new record or make changes/save to the record.
<?php
namespace App\Model\Behavior;
use Cake\ORM\Behavior\TimestampBehavior;
/**
* Modify built in CakePHP's Timestamp class's default config so no configuration is necessary for use in this project.
*/
final class CustomTimestampBehavior extends TimestampBehavior
{
/**
* Default config
*
* These are merged with user-provided config when the behavior is used.
*
* events - an event-name keyed array of which fields to update, and when, for a given event
* possible values for when a field will be updated are "always", "new" or "existing", to set
* the field value always, only when a new record or only when an existing record.
*
* refreshTimestamp - if true (the default) the timestamp used will be the current time when
* the code is executed, to set to an explicit date time value - set refreshTimetamp to false
* and call setTimestamp() on the behavior class before use.
*
* #var array
*/
protected $_defaultConfig = [
'implementedFinders' => [],
'implementedMethods' => [
'timestamp' => 'timestamp',
'touch' => 'touch',
],
'events' => [
'Model.beforeSave' => [
'CREATED_ON' => 'new',
'UPDATED_ON' => 'existing',
]
],
'refreshTimestamp' => true
];
}
and call it from your model table. Something like below:
public function initialize(array $config)
{
parent::initialize($config);
$this
->addBehavior('CustomTimestamp');
This way you don't need to call $this->model->touch($data) manually everytime. The behavior will take care of it whenever it creates or saves.
Ref: https://api.cakephp.org/3.0/class-Cake.ORM.Behavior.TimestampBehavior.html

Undefined index to empty variables (not required inputs)

im learning about angularjs and laravel. Basically i use angular to fetch my data in the forms and than send it to laravel to grab my variables and than create the record, the problem is with one input field (mobile), if i fill the mobile input it doesnt give me any problems, but if i leave it empty (since is not required input) it fails to create the record and give me a undefined index.
How can i make in Laravel to create anyway the record if one variable in my case is empty or not created?
php code:
public function registerUser($inputData)
{
$user = \DB::transaction(function () use ($inputData)
{
$user = User::create([
'email' => $inputData['user']['email'],
'name' => $inputData['user']['name'],
'surname' => $inputData['user']['surname'],
'mobilephone' => $inputData['user']['mobilephone'],
'birth_date' => Carbon::createFromFormat('d-m-Y', $inputData['user']['birth_date']),
]);
$user->save();
//Return the User
return $user;
});
//Return the User instance
return $user;
}
From what you are describing, when you don't fill in the mobile number the front end doesn't send an object which includes "$inputData['user']['mobilephone']". Which would cause an error in the script and prevent it from running. Please post the angular code responsible for transmitting the user information.
If my assumption is correct, you either need to check that these properties all exist in the $inputData before referencing them or have the front end add a dummy value when no value is provided.
OR What ever is holding the record (MySQL or whatever) may not allow this field to be null which would again prevent the insertion. But your description suggests this isn't it.

Difference in accessing variables in views

I've two controllers one is "Upload" which deals with images uploads and other is "Page" whid deals with the creation of pages of CMS now if in my "Upload" controller I load both the models i.e 'image_m' which deals with image upload and "page_m" which deals with the pages creation I've highlighted the relevant code my problem is if I access the variables in the view
$this->data['images'] = $this->image_m->get(); sent by this I can access in foreach loop as "$images->image_title, $images->image_path" etc
But the variable sent by this line ***$this->data['get_with_images'] = $this->page_m->get_no_parents();*** as $get_with_images->page_name, $get_with_images->page_id etc produces given error
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: upload/index.php
Line Number: 20
what is the difference between these two access levels one for $image & other for $get_with_images because I can only access its values as $get_with_images
class Upload extends Admin_Controller {
public function __construct() {
parent::__construct();
***$this->load->model('image_m');
$this->load->model('page_m');***
}
public function index($id = NULL) {
//var_dump($this->data['images'] = $this->image_m->get_with_images());
//$this->data['images'] = $this->image_m->get_with_images();
***$this->data['images'] = $this->image_m->get();***
$this->data['subview'] = 'admin/upload/index';
if ($id) {
$this->data['image'] = $this->image_m->get($id);
count($this->data['image']) || $this->data['errors'][] = 'Page Could not be found';
}
$id == NULL || $this->data['image'] = $this->image_m->get($id);
/*this calls the page_m model function to load all the pages from pages table*/
***$this->data['get_with_images'] = $this->page_m->get_no_parents();***
You are not posting all your code so its hard to tell but is it because you used $this-> in the controller, but you haven't done the same thing in the view?
In this case i would recommend not using $this-> because its not necessary. Also its much better to check for errors etc when you call the model so do something like
if ( ! $data['images'] = $this->image_m->get($id) ) {
// Failure -- show an appropriate view for not getting any images
// am showing $data in case you have other values that are getting passed
$this->load->view( 'sadview', $data ); }
else {
// Success -- show a view to display images
$this->load->view( 'awesomeview', $data ); }
so we are saying if nothing came back - the ! is a negative - then show the failure view. Else $data['images'] came back, and it will be passed to the view. note i have not had to use $this-> for anything and it won't be needed in the view.
Would also suggest using separate methods - have one method to show all images and a separate method like returnimage($id) to show an image based on a specific validated $id.
====== Edit
You can access as many models as you want and pass that data to the View. You have a different issue - the problem is that you are waiting until the View to find out - and then it makes it more difficult to figure out what is wrong.
Look at this page and make sure you understand the differences between query results
http://ellislab.com/codeigniter/user-guide/database/results.html
When you have problems like this the first thing to do is make a simple view, and echo out directly from the model method that is giving you problems. Its probably something very simple but you are having to look through so much code that its difficult to discover.
The next thing is that for every method you write, you need to ask yourself 'what if it doesn't return anything?' and then deal with those conditions as part of your code. Always validate any input coming in to your methods (even links) and always have fallbacks for any method connecting to a database.
On your view do a var_dump($get_with_images) The error being given is that you are trying to use/access $get_with_images as an object but it is not an object.
or better yet on your controller do a
echo '<pre>';
var_dump($this->page_m->get_no_parents());
exit();
maybe your model is not returning anything or is returning something but the data is not an object , maybe an array of object that you still need to loop through in some cases.

How to validate a pair of values from the same Model?

Use case
My use case is that I need to validate a Table Tennis score.
Form
<input name="data[MatchesPlayer][1][score]" type="number" id="MatchesPlayer1Score">
<input name="data[MatchesPlayer][2][score]" type="number" id="MatchesPlayer2Score">
Constraints
One score must be bigger than 11.
One score must be 2 points or greater than the other if the score is higher than 11.
Problem
When cake validates multiple rows from the same model, the model data is set to that record. This means that it's not possible to compare the two values as they aren't both available in $this->data. As I am using saveAll() each record is set to the model and then validated before it's saved.
Question
I'd like to know if there is a good way to validate this pair of data without resorting to saving it into the session or similar before I can validate it.
What I normally do here is I create a wrapper for the save method. This allows me to perform custom manipulation that would otherwise not be possible with model callbacks, or even use custom transactions etc.
In your case, it would be something like:
class MatchesPlayer extends Model {
protected $_saveData = null;
public function updateScore($data) {
$this->_saveData = $data;
try {
// You can use saveAll to validate
// only, and not actually save
$saved = $this->saveAll($data, array('validate' => 'only'));
} catch (Exception $e) {
// Catch exceptions here in case the
// saveAll is instead something that throws Exceptions
// Or your database uses exceptions
$saved = false;
}
$this->_saveData = null;
return $saved
}
}
You could then use $this->_saveData across the model. If you want to be clever with this, you could detect all sub-models that are being saved in the $data and then set the $this->_saveData on those as well - I would make this an AppModel method of course.
Note that you may want to throw exceptions from this updateScore() method when validation fails. Throwing an exception if validation fails - vs save - would allow you to set a custom flash message for the user as well, or even have an api that responds with a different status code.
Use custom validation rules in MatchesPlayer model, please check
http://book.cakephp.org/2.0/en/models/data-validation.html#adding-your-own-validation-methods

ExtJS 4: How can I configure a store to load models for a specific set of IDs?

For example, say I have a server API for loading people that handles requests like this: GET /people/?id=101,329,27
I'd like to build a Store (probably a custom class that extends Ext.data.Store) which--assuming it has a list of people IDs--causes the proxy to make a request like the one shown above so that the returned data is only for that subset of persons.
I saw the documentation regarding remote filtering, but my concern is that to use it I would first need to call store.load() which would load all persons, then call filter() to do remote filtering. I'd like to just load the subset of persons the first time.
Thanks for any advice!
Found a solution (although still open to hearing other ideas).
First, you can call a store's load() function with a config object that will be passed to an operation. The API docs for Ext.data.Operation make it clear that one of the config options is for an array of Filter objects, so you can do this:
var idFilter = Ext.create('Ext.util.Filter', {
property: 'id',
value: '100,200,300'
});
myStore.load({
filters: [ idFilter ]
});
This results in a request where the URL querystring contains ?filter=[{"property"%3Aid%2C"value"%3A100,200,300}] (in other words, a URL-encoded version of [{ property: 'id', value: '100,200,300'}]).
You can also just call myStore.filter('id', '100,200,300') without having called .load() first. Assuming you have remoteFilter=true in your store, this will make a request with the same query params shown agove.
Sidenote: you can change the keyword used for 'filter' by configuring the 'filterParam' config option for the proxy. For example, if filterParam=q, then the querystring shown above changes to: ?q=[{"property"%3Aid%2C"value"%3A100,200,300}]
Second, you can control "structure" of the filter in the querystring. In my case, I didn't want something like filter={JSON}, as shown above. I wanted a querystring that looked like this:?id=100,200,300
For this I needed to extend a proxy and override the default getParams() function:
Ext.define('myapp.MyRestProxy', {
extend: 'Ext.data.proxy.Rest',
/**
* Override the default getParams() function inherited from Ext.data.proxy.Server.
*
* Note that the object returned by this function will eventually be used by
* Ext.data.Connection.setOptions() to include these parameters via URL
* querystring (if the request is GET) or via HTTP POST body. In either case,
* the object will be converted into one, big, URL-encoded querystring in
* Ext.data.Connection.setOptions() by a call to Ext.Object.toQueryString.
*
* #param {Ext.data.Operation} operation
* #return {Object}
* where keys are request parameter names mapped to values
*/
getParams: function(operation) {
// First call our parent's getParams() function to get a default array
// of parameters (for more info see http://bit.ly/vq4OOl).
var paramsArr = this.callParent(arguments),
paramName,
length;
// If the operation has filters, we'll customize the params array before
// returning it.
if( operation.filters ) {
// Delete whatever filter param the parent getParams() function made
// so that it won't show up in the request querystring.
delete paramsArr[this.filterParam];
// Iterate over array of Ext.util.Filter instances and add each
// filter name/value pair to the array of request params.
for (var i = 0; i < operation.filters.length; i++) {
queryParamName = operation.filters[i].property;
// If one of the query parameter names (from the filter) conflicts
// with an existing parameter name set by the default getParams()
// function, throw an error; this is unacceptable and could cause
// problems that would be hard to debug, otherwise.
if( paramsArr[ queryParamName ] ) {
throw new Error('The operation already has a parameter named "'+paramName+'"');
}
paramsArr[ queryParamName ] = operation.filters[i].value;
}
}
return paramsArr;
}
});
You can also get your Model object to load a record of itself. From a controller you can do:
this.getRequestModel().load(requestID,{ //load from server (async)
success: function(record, operation) {
.....
}
}
where Request is a model class and requestID is an ID to look up. In this scenario Model object needs to define the proxy too:
proxy: {
type: 'ajax',
reader: {
type:'json',
root: 'data'
},
api: {
create : 'request/create.json', //does not persist
read : 'request/show.json'
}
}

Resources