phpmysqllaravelcode-readability

Defining the values of a field in a database in the Laravel code to make the code more readable


Currently, I am writing a laravel application with a part for sending messages between the staff at the company and the clients.
So, I have a field named "status" in the database. In this field, a value of one indicates that the message is waiting for an answer, a value of two indicates that it has been answered, and a value of three indicates that the message has been closed. There is a problem here, however. It's not clear what these numbers do when someone looks at my code.
Would there be any way for me to define this number or any other way to make my code more readable?
(I'm using laravel eloquent ORM) The code below is for the method that closes a conversation:

    public function close(Request $request)
    {
        $message = Message::find($request->message_id);
//        Status one indicates that a conversation has been closed
        $message->status = 1;
        $message->save();
        return \response($message, 200);
    }

Solution

  • Use constants in your Message model

    class Message
    {
        const STATUS_PENDING = 1;
        const STATUS_ANSWERED = 2;
        const STATUS_CLOSED = 3;
    //...
    }
    

    Then your code will be readable

    public function close(Request $request)
    {
        $message = Message::find($request->message_id);
        $message->status = Message::STATUS_CLOSED;
        $message->save();
        return \response($message, 200);
    }
    

    Or Even better, make it a method in your model on top of the constants values

    public function close(Request $request)
    {
        $message = Message::find($request->message_id);
        $message->close();
        return \response($message, 200);
    }
    

    That way you can in the future upgrade the method, for example

    class Message
    {
        public function close()
        {
            if ($this->status != self::STATUS_ANSWERED) {
                //log message closed without client answer
            }
            $this->status = STATUS_CLOSED;
            $this->save();
        }
    }