R
R
Rustam Akimov2018-09-06 12:06:55
Laravel
Rustam Akimov, 2018-09-06 12:06:55

How to properly validate data in Laravel?

API has Route

Route::get('/hint/{hintId}', '[email protected]');

There is a validator
<?php
namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class GetHint extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'hintId' => 'required|integer',
        ];
    }
}

And a function in the controller
public function show(Request $request)
    {
        $hint = Hint::where('id', $request->hintId)->first();

        return new HintResource($hint);
    }

Returns when requested
{
    "message": "The given data was invalid.",
    "errors": {
        "hintId": [
            "The hint id field is required."
        ]
    }
}

I can't figure out why it doesn't validate

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kairat Ubukulov, 2018-09-06
@ubukulov

Try using GetHint Request . That is like this:

use App\Http\Requests\GetHint as GetHintRequest;
......
public function show(GetHintRequest $request)
    {
        $hint = Hint::where('id', $request->hintId)->first();

        return new HintResource($hint);
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question