简体   繁体   中英

laravel retrieving request input returns null

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM