laravel validator get validated data code example

Example 1: validate laravel

$validatedData = $request->validate([
    'title' => ['required', 'unique:posts', 'max:255'],
    'body' => ['required'],
]);

Example 2: custom rule laravel validation

public function store()
{
    $this->validate(request(), [
        'song' => [function ($attribute, $value, $fail) {
            if ($value <= 10) {
                $fail(':attribute needs more cowbell!');
            }
        }]
    ]);
}

Example 3: valdidate laravel if falid

$validator = Validator::make($request->all(), [
    'name' => 'required|min:2|max:255'
]);

if ($validator->fails()) {
    return view('view_name');
} else {
    return view('view_name');
}

Example 4: validated() laravel

$request->validated();

Example 5: laravel get only validated data

public function store(Request $request)
{
   
    $validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

}