How can I solve “Type error: Argument 1 passed to

2019-03-04 10:34发布

问题:

My code like this :

public function functionA(Request $request)
{
    ...
    if($request->get('data')) {
        //echo '<pre>';print_r($request->get('data'));echo '</pre>';die();
        $data = json_decode($request->get('data'), true);
        $data = collect($data['data']);
        $this->validate($data, [
            'id'=>'required|numeric',
            'quantity'=>'required|numeric',
        ]);
        $input = $data->only('id', 'quantity','request_date');
        ...
    }
}

The result of echo '<pre>';print_r($request->get('data'));echo '</pre>';die(); like this :

{"data":{"id":46,"quantity":1,"total":100000,"information":"chelsea","name":"Hazard","request_date":"14-08-2017 16:26:00"},"expired":"2017-08-14T06:27:00.738Z"}

If the code executed, there exist error like this :

Type error: Argument 1 passed to App\Http\Controllers\Controller::validate() must be an instance of Illuminate\Http\Request,...

How can I solve the error?

回答1:

The first parameter passed to validate should be an instance of Illuminate\Http\Request.

So you need to pass the $request object to validate method as the first parameter like this

$this->validate($request, [
    'validation' => 'rules',
]);

If you are receiving input as JSON make sure Content-Type header of the request is set to application/json

jQuery ajax example

$.ajax({
    url: url,
    type: 'POST',
    data: {
        'id': 'value', 
        'quantity': 'value'
    },
    dataType: 'json',
    contentType: 'application/json'
});


回答2:

If you are using use Request; in your controller, then replace it with,

use Illuminate\Http\Request;