0

I'm using this code for User Sign Up in Laravel:

class UsersController extends Controller
{
  public function register(Request $request)
  {
          $validatedData = $request->validate([
              'name' => 'required|string|max:255',
              'email' => 'required|string|email|max:255|unique:users',
              'password' => 'required|string|min:8',
              'phone' => 'required|unique:users',
              'type' => 'boolean',
              'verified' => 'boolean'
  ]);
  
          $user = User::create([
              'name' => $validatedData['name'],
              'email' => $validatedData['email'],
              'phone' => $validatedData['phone'],
              'type' => $validatedData['type'],
              'verified' => $validatedData['verified'],
              'password' => Hash::make($validatedData['password']),
         ]);
  
  $token = $user->createToken('auth_token')->accessToken;
  
  return response()->json([
                    'user' => $user,
                    'access_token' => $token,
                     'token_type' => 'Bearer',
  ]);
  }

As you can see , some of my field are unique , so I want to display a message in my front side that displays the error from the back side.

Exemple : When a user enters a used phone number , I want to return an error saying : this phone number has been used .

How can I achieve this ? Thank you.

1
  • Find record in User table using phone number, if record exists, then return this phone number has been used, otherwise, do something else Commented May 12, 2022 at 1:40

1 Answer 1

1

You can get a User record from the database by phone. If the record exists, then do your logic

class UsersController extends Controller
{
  public function register(Request $request)
  {
          $validatedData = $request->validate([
              'name' => 'required|string|max:255',
              'email' => 'required|string|email|max:255|unique:users',
              'password' => 'required|string|min:8',
              'phone' => 'required|unique:users',
              'type' => 'boolean',
              'verified' => 'boolean'
          ]);
  
        // get a user record by phone
        $record = User::where('phone', $validatedData['phone'])->find();
        if (!empty($record)) {
            return response()->json([
                'error' => 'this phone number has been used'
                ])
        }

         //..... 
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.