Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

laravel i have request field type. if type is user i want to test if user exists by id,…

  1. User

    laravel i have request field type. if type is user i want to test if user exists by id, if type is worker i want ti test if worker exists by id.... how?

  2. Assistant

    Assuming you have a request field called id and a field called type which can either be user or worker, you can use Laravel's validation feature to create a custom validation rule that tests if the specified id is valid for the specified type.

    Here's an example of how to create the custom validation rule:

    use Illuminate\Support\Facades\Validator;
    use App\Models\User; // replace with your user model
    use App\Models\Worker; // replace with your worker model
    
    Validator::extend('valid_id_for_type', function ($attribute, $value, $parameters, $validator) {
        $type = $validator->getData()['type'];
    
        switch ($type) {
            case 'user':
                return User::find($value) !== null;
            case 'worker':
                return Worker::find($value) !== null;
            default:
                return false;
        }
    });
    

    This creates a new validation rule called valid_id_for_type. When you want to validate a request that has a type and id field, you can use this validation rule like this:

    $request->validate([
        'type' => 'required|in:user,worker',
        'id' => 'required|integer|valid_id_for_type',
    ]);
    

    This will make sure that the type field is either user or worker, and that the id field is a valid id for the given type. If the validation fails, Laravel will automatically return an error response.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.