laravel request validation rules code example

Example 1: laravel validator make custom message

$rules = [
        'name' => 'required',
        'email' => 'required|email',
        'message' => 'required|max:250',
    ];

    $customMessages = [
        'required' => 'The :attribute field is required.'
    ];

    $this->validate($request, $rules, $customMessages);

Example 2: laravel unique validation

/**
 * Store a new blog post.
 *
 * @param  Request  $request
 * @return Response
 */

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

    // The blog post is valid...
}

Example 3: laravel validation

/**
 * Store a new blog post.
 *
 * @param  Request  $request
 * @return Response
 */
public function store(Request $request)
{
    $validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    // The blog post is valid...
}

Example 4: laravel request validation rules for create and update

public function rules()
    {
        $rules = [
            'name' => 'required|string|unique:products|max:255',
        ];

        if (in_array($this->method(), ['PUT', 'PATCH'])) {
            $product = $this->route()->parameter('product');

            $rules['name'] = [
                'required',
                'string',
                'max:255',
                Rule::unique('loan_products')->ignore($product),
            ];
        }

        return $rules;
    }