laravel i have request field type. if type is user i want to test if user exists by id,…
- 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?
- Assistant
Assuming you have a request field called
idand a field calledtypewhich can either beuserorworker, 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 atypeandidfield, 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
typefield is eitheruserorworker, and that theidfield is a valid id for the given type. If the validation fails, Laravel will automatically return an error response.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.