Conditionally validate request fields trong Laravel Chuyên mục PHP và Laravel 2023-08-02 1.5k Lượt xem 50 Lượt thích 0 Bình luận

Cách thông thường để validating các thuộc tính request trong Laravel là tạo Illuminate\Support\Facades\Validator instance với các static rules không bao giờ thay đổi như này.
<?php
namespace App\Http\Controllers\API\v1\Users;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Entities\Models\User;
class UserController extends Controller
{
public function store(Request $request)
{
// validate incoming request
$validator = Validator::make($request->all(), [
'email' => 'required|email|unique:users',
'name' => 'required|string|max:50',
'password' => 'required',
'subscription_type' => 'required'
]);
if ($validator->fails()) {
Session::flash('error', $validator->messages()->first());
return redirect()->back()->withInput();
}
}
}
Bạn pass tất cả các request attributes cùng với các validation rules mà bạn muốn validate, dưới dạng một mảng cho đối số thứ hai của phương thức make .
Bây giờ, có thể có một tình huống trong đó bạn chỉ muốn validate một số trường nếu một số điều kiện nhất định được đáp ứng. Có nghĩa là bạn muốn validate có điều kiện. Bạn sẽ làm điều này như thế nào?
Sử dụng sometimes method
Điều này có thể được thực hiện bằng cách sử dụng sometimes trên validator instance. Vì vậy, chẳng hạn như trong ví dụ trước, nếu bạn chỉ muốn validate thuộc tính payment_method khi subscription_type được đặt thành premium, thì bạn có thể thực hiện như sau.
$validator->sometimes('payment_method', 'required', function ($input) {
return $input->subscription_type === 'premium';
});
Tại đây, tham số $input được pass đến Closure sẽ là một instance của Illuminate\Support\Fluent và có thể được sử dụng để truy cập input và file của bạn.
Để tiến xa hơn, bạn có thể thêm validations có điều kiện cho một số trường cùng một lúc như vậy.
Bình luận (0)