Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change value of a request parameter in laravel

Tags:

laravel

People also ask

What is request() in Laravel?

Laravel's Illuminate\Http\Request class provides an object-oriented way to interact with the current HTTP request being handled by your application as well as retrieve the input, cookies, and files that were submitted with the request.

How do I get params in laravel?

Method 1: $request->route('parameter_name') One way is by using $request->route('parameter_name') ., where parameter_name refers to what we called the parameter in the route. In the handle method within the DumpMiddleware class created in the app/Http/Middleware/DumpMiddleware. php file.

Does laravel have request?

The has MethodThe $request->has() method will now return true even if the input value is an empty string or null . A new $request->filled() method has been added that provides the previous behaviour of the has() method.


Try to:

$requestData = $request->all();
$requestData['img'] = $img;

Another way to do it:

$request->merge(['img' => $img]);

Thanks to @JoelHinz for this.

If you want to add or overwrite nested data:

$data['some']['thing'] = 'value';
$request->merge($data);

If you do not inject Request $request object, you can use the global request() helper or \Request:: facade instead of $request


Use merge():

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

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


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);

Use add

$request->request->add(['img' => $img]);

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]);

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.