How to modify Request values in laravel?

Jagadesha NH picture Jagadesha NH · Jul 18, 2015 · Viewed 29.8k times · Source

I have the following code,

my question is how to modify Request values?

public function store(CategoryRequest $request)
{
    try {
        $request['slug'] = str_slug($request['name'], '_');
        if ($request->file('image')->isValid()) {
            $file = $request->file('image');
            $destinationPath = public_path('images/category_images');
            $fileName = str_random('16') . '.' . $file->getClientOriginalExtension();
            $request->image = $fileName;
            echo $request['image'];
            $file->move($destinationPath, $fileName);
            Category::create($request->all());
            return redirect('category');
        }
    } catch (FileException $exception) {
        throw $exception;
    }
}

But,

on each request the output of

echo $request['image'];

outputs some text like /tmp/phpDPTsIn

Answer

PapaHotelPapa picture PapaHotelPapa · Apr 7, 2016

You can use the merge() method on the $request object. See: https://laravel.com/api/5.2/Illuminate/Http/Request.html#method_merge

In your code, that would look like:

public function store(CategoryRequest $request)
{
    try {
        $request['slug'] = str_slug($request['name'], '_');
        if ($request->file('image')->isValid()) {
            $file = $request->file('image');
            $destinationPath = public_path('images/category_images');
            $fileName = str_random('16') . '.' . $file->getClientOriginalExtension();
            $request->merge([ 'image' => $fileName ]);
            echo $request['image'];
            $file->move($destinationPath, $fileName);
            Category::create($request->all());
            return redirect('category');
        }
    } catch (FileException $exception) {
        throw $exception;
    }
}

In spite of the methods name, it actually replaces any values associated with the member names specified by the keys of the parameter rather than concatenating their values or anything like that.