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

前端 未结 13 2196
闹比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:45

    Based on my observations:

    $request->request->add(['variable' => 'value']); will (mostly) work in POST, PUT & DELETE methods, because there is value(s) passed, one of those is _token. Like example below.

    @csrf
    public function process(Request $request, $id){ $request->request->add(['id' => $id]); }

    But [below code] won't work because there is no value(s) passed, it doesn't really add.

    PROCESS
    
    public function process(Request $request, $id){
        $request->request->add(['id' => $id]);
    }
    


    When using GET method you can either declare Request and assign value(s) on it directly. Like below:

    public function process($id){
        $request = new Request(['id' => $id]);
    }
    

    Or you can use merge. This is better actually than $request->request->add(['variable' => 'value']); because can initialize, and add request values that will work for all methods (GET, POST, PUT, DELETE)

    public function process(Request $request, $id){
        $request->merge(['id' => $id]);
    }
    

    Tag: laravel5.8.11

提交回复
热议问题