dingo / api

A RESTful API package for the Laravel and Lumen frameworks.
BSD 3-Clause "New" or "Revised" License
9.32k stars 1.25k forks source link

instance of Dingo\\Api\\Http\\Request given Error #1761

Open laravel-devs-crescode opened 4 years ago

laravel-devs-crescode commented 4 years ago
Q A
Bug? no yes
New Feature? no
Framework Laravel
Framework version 8
Package version 3.0.4
PHP version ^7.3 ^8.0

Actual Behaviour

I am trying to validate the input of user from the service. I am following a service repository pattern here. So I have created a Validator for the users input I have added it to the Service class but I get an error on Postman when trying to post data.

Error

"message": "Argument 1 passed to App\\Services\\UserService::saveUser() must be an instance of App\\Requests\\UserStoreRequest, instance of Dingo\\Api\\Http\\Request given, called in C:\\laragon\\www\\nextserver\\app\\Http\\Controllers\\Api\\UserController.php on line 28",

Controller

    protected $userService;
    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

    public function store(Request $request) 
    {
        try {
            $result['data'] = $this->userService->saveUser($request);
        }
        catch (\Exception $e) {
            $result = [
                'error' => $e->getMessage(),
                'line' =>$e->getLine()
            ];
        }

    }

Request / Validation Class

use Illuminate\Foundation\Http\FormRequest;
class UserStoreRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }
    public function rules()
    {
        return [
            'email' => 'required|email|unique:users',
            'name' => 'required|unique:users',
            'password' => 'required',
            'sex' => 'required',
        ];
    }

    public function messages()
    {
        return [
            'email.required' => 'Email field is empty!',
            'name.required' => 'Name field is empty!',
            'password.required' => 'Password field is empty!',
            'sex.required' => 'Sex field is empty!'
        ];
    }
}

Service Class

use App\Requests\UserStoreRequest;
use App\Repositories\UserRepository;
class UserService
{
    protected $userRepository;
    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }
    public function saveUser(UserStoreRequest $data) 
    {
        $validData = $data->validated();
        $result = $this->userRepository->save($validData);
        return $result;
    }
}

How do I fix this issue?

specialtactics commented 4 years ago

Which class is "Request" in your first file?