Search code examples
databaselaraveltry-catchresponse

How to match an input value in Laravel match before saving to sqlite database


I am trying to make the value of $input data to first match with one the pluck array values in a user table in the database before the input is saved and a response of 'its a match be given'. I trying to put these checks on an API I'm making. I'm new to laravel API and I will appreciate the help. Thank you

public function create(Request $request)
    {
        //
        $this->validate($request, [
            'inputed_number' => 'required|unique:users',
            'user_id' => 'required'
        ]);

        try {
            Auth::user();
            $phonenumber = new PhoneNumber();
            $phonenumber->inputed_number = $request->inputed_number;
            $phonenumber->user_id = $request->user_id;
            
            if($this->user->phonenumber()->save($phoneuumber)){
        $user = User::all();
        $input = $request->only('inputed_number');
        $user_number = $user->pluck('phone');
        foreach ($input as $phone) {
             if ($phone !== $user_number) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid number',
                    'data' => $phone,
                ], Response::HTTP_UNAUTHORIZED);
            }

            return response()->json([
                    'success' => true,
                    'message' => 'Its a match!!',
                    'data' => $phone,
            ]);
        }
    }
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'You have already inputted this number.',
            ], Response::HTTP_UNAUTHORIZED);
        }

    }

Solution

  • just get the whole user object with Auth:user no need for the pluck statement, you can access values directly via user object,

    $user = Auth:user();
     $input = $request->only('inputed_number');
    if($user->phone !== $input ) {
       //perform this code
    }
    

    If you want to match phone numbers from all users,

    //get all users where phone number matches
    $users = User::where('phone', $input)->get();
    
    // iterate through $users rows
    foreach ($users as $user) {
        ///do some thing
    }