Search code examples
laravellaravel-validation

Do I need to validate the Request in Controller after?


I have this StoreMessageRequest

public function rules(): array {
        return [
            'message' => [
                'required',
                'string',
                'max:60',
            ],
        ];
    }

which leads to MessageController

public function store(StoreMessageRequest $request, Message $message) {
     ......
}

I can then run query of

$message = new Message([
        'user_id' => auth()->id(),
        'message' => $request->message
    ]);

    $message->save($message);

is this safe or should I use $request->safe()->message ~ $validated = $request->safe()->all(); or $validated = $request->validated();?


Solution

  • The store() method will only be called if validation passes.

    $request->safe()->message would almost be the same as $request->message the difference being when using safe() you get a ValidatedInput instance with the validated data

    $request->validated() and $request->safe()->all() is the exact same thing. But every time you call the safe() method you are creating a new ValidatedInput instance

    $request->safe() is the same as new ValidatedInput($request->validated())

    $request->all() includes non valid data