How to change value of a request parameter in laravel

前端 未结 7 1739
太阳男子
太阳男子 2020-12-02 21:40

I need to change value of my request parameter like this:

$request->name = \"My Value!\";

I use

相关标签:
7条回答
  • 2020-12-02 22:08

    If you need to customize the request

    $data = $request->all();
    

    you can pass the name of the field and the value

    $data['product_ref_code'] = 1650;
    

    and finally pass the new request

    $last = Product::create($data);
    
    0 讨论(0)
  • 2020-12-02 22:09

    It work for me

    $request = new Request();
    $request->headers->set('content-type', 'application/json');     
    $request->initialize(['yourParam' => 2]);
    

    check output

    $queryParams = $request->query();
    dd($queryParams['yourParam']); // 2
    
    0 讨论(0)
  • 2020-12-02 22:11

    If you use custom requests for validation, for replace data for validation, or to set default data (for checkboxes or other) use override method prepareForValidation().

    namespace App\Http\Requests\Admin\Category;
        
    class CategoryRequest extends AbstractRequest
    {
        protected function prepareForValidation()
        {
            if ( ! $this->get('url')) {
                $this->merge([
                    'url' => $this->get('name'),
                ]);
            }
            $this->merge([
                'url'    => \Str::slug($this->get('url')),
                'active' => (int)$this->get('active'),
            ]);
        }
    }
    

    I hope this information will be useful to somebody.

    0 讨论(0)
  • 2020-12-02 22:13

    Use merge():

    $request->merge([
        'user_id' => $modified_user_id_here,
    ]);
    

    Simple! No need to transfer the entire $request->all() to another variable.

    0 讨论(0)
  • 2020-12-02 22:21

    Great answers here but I needed to replace a value in a JSON request. After a little digging into the code, I came up with the following code. Let me know if I'm doing something dumb.

    $json = $request->json()->all();
    $json['field'] = 'new value';
    $request->json()->replace($json);
    
    0 讨论(0)
  • 2020-12-02 22:28

    If you need to update a property in the request, I recommend you to use the replace method from Request class used by Laravel

    $request->replace(['property to update' => $newValue]);
    
    0 讨论(0)
提交回复
热议问题