簡體   English   中英

Laravel 更改輸入值

[英]Laravel change input value

在 laravel 中,我們可以通過Input::get('inputname')獲取輸入值。 我嘗試通過執行此Input::get('inputname') = "new value";來更改值 . 但是,我收到錯誤消息,說Can't use function return value in write context

我們是否可以更改輸入值,以便稍后調用Input::get('inputname')時將獲得新的修改值?

謝謝。

您可以使用Input::merge()替換單個項目。

Input::merge(['inputname' => 'new value']);

或者使用Input::replace()替換整個輸入數組。

Input::replace(['inputname' => 'new value']);

是文檔的鏈接

如果你想在 Laravel 5 中這樣做,你可以使用Request類中的merge()方法:

class SomeController extends Controller
{
    public function someAction( Request $request ) {

        // Split a bunch of email addresses
        // submitted from a textarea form input
        // into an array, and replace the input email
        // with this array, instead of the original string.
        if ( !empty( $request->input( 'emails' ) ) ) {

            $emails = $request->input( 'emails' );
            $emails = preg_replace( '/\s+/m', ',', $emails );
            $emails = explode( ',', $emails );

            // THIS IS KEY!
            // Replacing the old input string with
            // with an array of emails.
            $request->merge( array( 'emails' => $emails ) );
        }

        // Some default validation rules.
        $rules = array();

        // Create validator object.
        $validator = Validator::make( $request->all(), $rules );

        // Validation rules for each email in the array.
        $validator->each( 'emails', ['required', 'email', 'min: 6', 'max: 254'] );

        if ( $validator->fails() ) {
            return back()->withErrors($validator)->withInput();
        } else {
            // Input validated successfully, proceed further.
        }
    }
}

如果您的意思是要覆蓋輸入數據,可以嘗試執行以下操作:

Input::merge(array('somedata' => 'SomeNewData'));

試試這個,它會幫助你。

$request->merge(array('someIndex' => "yourValueHere"));

我也發現了這個問題,可以用下面的代碼解決:

public function(Request $request)
{
    $request['inputname'] = 'newValue';
}

問候

我正在使用 Laravel 8。以下內容對我有用: $request->attributes->set('name', 'Value');

我用 Raham 的回答來解決我的問題。 但是,當我需要它與其他數據處於同一級別時,它會將更新的數據嵌套在一個數組中。 我用了:

$request->merge('someIndex' => "yourValueHere");

請注意其他 Laravel 新手,我使用 merge 方法來說明 Laravel 7 更新表單中的空復選框值。 更新表單上取消選中的復選框不會返回 0,它不會在更新請求中設置任何值。 因此,該值在數據庫中保持不變。 如果不存在任何內容,您必須檢查設置值並合並新值。 希望對某人有所幫助。

只是快速更新。 如果用戶沒有選中一個框並且我需要在數據庫中輸入一個值,我會在我的控制器中執行以下操作:

    if(empty($request->input('checkbox_value'))) {
        $request->merge(['checkbox_value' => 0]);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM