2

I have Laravel 6.0 with something like this using the request()->all(); helper to create a new row on the database...

$input = request()->all();
Service::create($input);

I want to add two variables to it manually so that we don't need the user to add them manually. I have tried variations on this...

$time = time();
$input = array_merge(request()->all(), ['serviceSite' => 'companyname', 'serviceOrderedTime' => $time]);
Service::create($input);

Is there a way to do this with the request() helper or do I have to use an alternative method?

sdexp
  • 756
  • 4
  • 18
  • 36
  • You could make those columns have default values in DB already, not needing you to add them manually here? – nice_dev Sep 20 '19 at 11:21

4 Answers4

6

Try this.

$time = time();
$input = $request->all();
$input['serviceSite'] = 'companyname';
$input['serviceOrderedTime'] = $time;
Service::create($input);

Make sure serviceSite and serviceOrderedTime fillable in your model.

IF you want to merge it with $request then you can do like this.

$request->merge(["key"=>"value"]);

As your Way.

  $time = time(); 
  $request->request->add(['serviceSite' => 'companyname','serviceOrderedTime'=>$time]);
  Service::create($request->all());
Dilip Hirapara
  • 14,810
  • 3
  • 27
  • 49
1

There is a helper function in laravel collection called add you can use it like this

$request->add(['serviceSite' => 'companyname']);
$request->add(['serviceOrderedTime' => $time]);
Service::create($request->all());

or you can make it by the common way

$request = request()->all();
$request['serviceSite'] = 'companyName';
$request['serviceOrderedTime'] = $time;
Joseph
  • 5,644
  • 3
  • 18
  • 44
1

This is how you can set a variable to your request:

$request->request->set('serviceSite', 'serviceSite');
$request->request->set('serviceOrderedTime', $time);

In order to allow mass assignment, the serviceSite and serviceOrderedTime may be include in your $fillable model property.

Hope it helps.

Mateus Junges
  • 2,559
  • 1
  • 12
  • 24
0

If you are trying to add a new key value in FormRequest file, you can do it

class CreateKubernetesRequest extends FormRequest
{

    public function rules()
    {
        $rules = [
            'zone' => 'required|exists:zone_offerings,name',
        ];
        $this->request->add(['version_id' => "SOME ID"]);

        return $rules;
        
    } 

}
Abhi Burk
  • 2,003
  • 1
  • 14
  • 21