Q&A:
I would like to set some default values to avoid empty fields.
I want to set the default values in the Controller not the html
Forms placeholders don't work as filled field
I want to still be able to outputs the error if some of the key value is missing
I've found just the right way to acomplish this by using array merge:
array_merge($requested, $default)
The keys from the first array will be preserved! You should check php doc.
Then proceed (create & redirect).
Unspecified keys will throw errors, also you should check 'strict' => false in the config/database.php if you run into a problem.
{NameController.php}
$default = array(['image' => 'http://placehold.it/250x225']);
$request = request(['user' => request('user')]);
$input = array_merge($request, $default);
{Model}::create($input);
return redirect('{view}');
BE AWARE that this method leads to MassAssigmentExeption if you didn't set the $guarder or $protected fields in the {Model}.
I am new to stack so please tell me if something is wrong, thx.
Related
I'm trying to figure out how to properly code the update() function in eloquent to return either 0 or 1 based on user input in a form. For example, if I hit the update button without making any changes, it returns 1. Shouldn't it return 0?
I tried researching for solutions like here in stackoverflow to see if anyone has the same problem as I am facing. But so far not luck. I also tried modifying the code, but no luck.
public function update(Request $request, $id)
{
$UCPost = UCPost::find($id);
$UCPost->gown_2019 = $request->input('Gown2019');
$UCPost->gown_2017_2018 = $request->input('Gown20172018');
$UCPost->gown_2016 = $request->input('Gown2016');
$UCPost->gown_2015 = $request->input('Gown2015');
$UCPost->Light_Blue = $request->input('LightBlue');
$UCPost->Seconds = $request->input('Seconds');
$UCPost->Velveteen = $request->input('Velveteen');
$UCPost->Velveteen_discolored = $request->input('Velveteen_discolored');
$UCPost->Rental = $request->input('Rental');
$UCPost->Rentals_Out = $request->input('Rentals_Out');
$UCPost->Rentals_Left = $request->input('Rentals_Left');
return $UCPost->where('id', $id)->update(
[
'gown_2019' => $UCPost->gown_2019,
'gown_2017_2018' => $UCPost->gown_2017_2018,
'gown_2016' => $UCPost->gown_2016,
'gown_2015' => $UCPost->gown_2015,
'Light_Blue' => $UCPost->Light_Blue,
'Seconds' => $UCPost->Seconds,
'Velveteen' => $UCPost->Velveteen,
'Velveteen_discolored' => $UCPost->Velveteen_discolored,
'Rental' => $UCPost->Rental ,
'Rentals_Out' => $UCPost->Rentals_Out,
'Rentals_Left' => $UCPost->Rentals_Left
]
);
}
The code above as I mentioned earlier, it always returns 1 regardless of any changes made to the form. I want it to return 0 if there are no changes by the user or if they accidentally hit the update button. I'm trying to find the equivalent of mysqli_affected_rows in Eloquent.
You are calling the update() method on your model. This will return 1 if the update was successful. It doesn't matter if there were any changes made, always 1 on successful update.
If you would like to only save to the database if there are changes, you can use the save() method instead, which checks to see if changes are present, and only writes to the database if the data is different. You have already created code to do this, by setting the model to have all of the new data from the sheet, so a simple save() at the end (with a check to see if it saves), will do what you want.
However, your current code is doing a lot of extra work. You are assigning all the variables to the model, and then updating based on that assignment of data to the model. You don't have to do all that assignment again in the update method. Once you have set the fields, you can save immediately, you don't have to re-assign all the variables. So:
$UCPost->gown_2019 = $request->input('Gown2019');
// etc..
$UCPost->Rentals_Left = $request->input('Rentals_Left');
$UCPost->save();
Will get you where you want to go and will only save if different.
If you have control over your form, and can change the form element names to match your database, this can be even easier. You can do all of this in one line:
$UCPost->update($request->all());
If you want to check if the model is dirty just call isDirty():
if($UCPost->isDirty()){
// changes have been made
}
Finally, if you want to verify if anything was changed after either method (save or update):
if ($UCPost->wasChanged()) {
// changes have been made
}
Hope this helps
I use Laravel 5.8, and I want simply use a default value for description if it's empty, and take summary.
// summary variable request is equal to "test"
$summary = $request->get('summary', null);
$request->get('description', $summary)
But, the field is present, empty, and description give me null instead of summary value. Summary value is "test".
To get information from a request you should use get(), input() or the name directly. There is no documentation for the get method on requests for recent Laravel versions. For the input method on Laravel 5.8 the documentation says
You may pass a default value as the second argument to the input method. This value will be returned if the requested input value is not present on the request
It says it only works if it is not present so I would do it as simple as this
$description = $request->description ? $request->description : $request->summary
It really depends on what you want to achieve after all this and how you want your data.
Possible Solutions
My first impressions were that the data may not be being sent through correctly but upon looking over your code again, I realized you are using the more deprecated function ->get('description').
Try using ->input('description) instead. I personally have never used ->get(), so maybe this could be the problem.
https://laravel.com/docs/5.8/requests
I am using Laravel 5.4 and building API for Android and Iphone. I have set default value to null in phpmyadmin but my mobile developers do not want null values in response. There are many APIs so I am looking for short and perfect method.
I tried to find something in Laravel model that can help me. I tried following code as well.
Also tried setting default value in phpmyadmin but it does not accepts default: "As defined" is equal to empty value.
Third option could be to loop through laravel Model response and convert null to empty or zero based on data type but that will increase processing time and will increase our most of work as well.
public static function boot() { parent::boot();
self::creating(function ($my_model) {
$my_model->some_prop = $my_model->some_prop >= 42 ? $my_model->some_prop: defaultValue();
});}
Is there something in Laravel in Model section or somewhere else where I can set default value to empty fields when field does contain any value or is there any other solution or suggestion means how I can handle this problem?
Sorry if this question is asked elsewhere, but I've searched everywhere but couldn't find the answer. Well, I'm facing this problem on Laravel 5.0, when i try to get a variable from a request, Im getting null value on Production Server but im getting an empty string on the Development Server. The value is not present on the request, ie the field was empty when the form was submitted. eg.
// ProductController
public function store(Request $request) {
// this field is actually empty in the submitted form
$price = $request->price;
// when it gets to the server this is how this value looks like :
// $price in production server : null
// $price in development server : ''
}
When i try to save the object to a database like
Product::save($request->only('name', 'price'));
I get this error(only on production server)
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'price'
cannot be null
NOTE that the price column has 'default 0' on mysql table
Why is this happening?
UPDATE:
All this time i thought the request->input() method returned empty string('') if the field was not present. but just know i looked at the laravel source to see this :
public function input($key = null, $default = null)
{
$input = $this->getInputSource()->all() + $this->query->all();
return array_get($input, $key, $default);
}
here it returns null as the default value. then why am i getting empty string on development server?
This is happening because mysql inserts the default value if you don't define anything. In this case Laravel sends a value, which is null. You should not use Request::only, instead use an array.
It's always good to be specific, it makes your code readable and consistent.
Input Trimming & Normalization
By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware are listed in the stack by the App\Http\Kernel class. These middleware will automatically trim all incoming string fields on the request, as well as convert any empty string fields to null. This allows you to not have to worry about these normalization concerns in your routes and controllers.
If you would like to disable this behavior, you may remove the two middleware from your application's middleware stack by removing them from the $middleware property of your App\Http\Kernel class.
From: https://laravel.com/docs/5.4/requests#input-trimming-and-normalization
We're using Zend Framework 1.12 and in several actions we have:
$postParams = $this->getAllParams();
...
$domainModel->update($postParams)
I was wondering if it's a good approach of handling params. Or is it better to define what parameters we want to get like:
$postParams = array(
'email' => $this->_getParam('email'),
'company' => $this->_getParam('company')
)
Or maybe use array intersection function to filter out unexpected parameters?
Best practice should be using
$postParams = array(
'email' => $this->_getParam('email'),
'company' => $this->_getParam('company')
);
Using array intersection may work (for checking the keys not values of course!)
Why is passing all params to $domainModel->update not so good?
Depends on logic of update but assuming that parameters are getting into database query, by manipulating http request i can inject some additional code or params into db query - maybe update the field you do not want to update by that particular action.
Downside of this approach is that when you change your model, you have to check your code for these params.
If all columns in table (including IDs) can be changed, you can use getAllParams. Except one problem: POST can contain variables that are not table columns, so you will get an error on update (column '...' not found).
Its not a good idea to pass all post parameters to model directly. Sometimes you may not want pass specific values to model.
Second, you may want to set some default values to the data in case its not provided in that case you can do $this->_getParam('company', DEFAULT_VALUE)
But i would say that usage of any method depends on your requirements and then you need to pick one which is most suitable for you.