Laravel is there a way to add values to a request array

前端 未结 13 2125
闹比i
闹比i 2020-12-07 15:24

I come across a situation in Laravel while calling a store() or update() method with Request parameter to add some additional value to the request before calling Eloquent fu

相关标签:
13条回答
  • 2020-12-07 15:58

    enough said on this subject but i couldn't resist to add my own answer. I believe the simplest approach is

    request()->merge([ 'foo' => 'bar' ]);
    
    0 讨论(0)
  • 2020-12-07 16:00

    In laravel 5.6 we can pass parameters between Middlewares for example:

    FirstMiddleware

    public function handle($request, Closure $next, ...$params)
    {
        //some code
        return $next($request->merge(['key' => 'value']));
    }
    

    SecondMiddleware

    public function handle($request, Closure $next, ...$params)
    {
        //some code
        dd($request->all());
    }
    
    0 讨论(0)
  • 2020-12-07 16:00

    To add a new parameter for ex: newParam to the current Request Object, you can do:

    $newParam = "paramvalue";
    $request->request->add(['newParam' => $newParam]);
    

    After adding the new parameter, you would be able to see this newly added parameter to the Request object by:

    dd($request);//prints the contents of the Request object
    
    0 讨论(0)
  • 2020-12-07 16:02
    $request->offsetSet(key, value);
    
    0 讨论(0)
  • 2020-12-07 16:03

    You can access directly the request array with $request['key'] = 'value';

    0 讨论(0)
  • 2020-12-07 16:07

    Referring to Alexey Mezenin answer:

    While using his answer, I had to add something directly to the Request Object and used:

    $request->request->add(['variable', 'value']);
    

    Using this it adds two variables :

    $request[0] = 'variable', $request[1] = 'value'
    

    If you are a newbie like me and you needed an associate array the correct way to do is

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

    Hope I saved your some time

    PS: Thank you @Alexey, you really helped me out with your answer

    0 讨论(0)
提交回复
热议问题