laravelapisha512

Laravel - Hash input using SHA512


I am creating an API POST request, but I want to hash some of the user input (referenceID and phone_no) and save into hash field using SHA512. I want to put it in the Controller.

I have create the Model Class and also the Controller

Model

    protected $fillable = [
        'referenceID' ,
        'phone_no',
        'hash'
    ]; 

Controller

    public function store(Request $request)
    {
        $request->validate([
            'referenceID' => 'required',
            'phone_no' => 'required',
        'hash' => 'required'
        ]);

        $valrequest = Task::create($request->all());

        return response()->json([
            'message' => 'Great success! New validation request created',
            'valrequest' => $valrequest, 201
        ]);
    }

I want to hash the user input (referenceID and phone_no) and save into the hash field using SHA512. I want to put it in the Controller. How do I do this.


Solution

  • Should work fine like this, but the code's not tested at all and there's like a million different ways to do this. You won't need to validate the hash because it's no user input.

    public function store(Request $request)
    {
        $request->validate([
            'referenceID' => 'required',
            'phone_no' => 'required',
        ]);
    
        $referenceID = $request->referenceID;
        $phone_no = $request->phone_no;
        $hash = hash('sha512', $referenceID . $phone_no);
    
        $valrequest = Task::create(compact('referenceID', 'phone_no', 'hash'));
    
        return response()->json([
            'message' => 'Great success! New validation request created',
            'valrequest' => $valrequest, 201
        ]);
    }