Skip to content
Advertisement

Numeration of documents on PHP

PHP, Laravel 6.0: I can’t write a working static function or a variable for getting numeration of my documents with increment. Every time I create a document it should set its number (Document #1, #2, #3…etc)

I have checked and tried similar questions on StackOverflow but they didn’t work.

I’ve got an Observer Class which should handle the “creating” event and use that function for setting a new number. Here are my tries:

class DocumentObserver
{
    /**
     * Found this one on StackOverflow but it didn't work
     */
    public function currentNum()
    {
        static $num = 6;
        $num++;
        return $num;
    }

    /**
     * Tried to use a property but it didn't work as well
     */
    public static $currentNumber = 0;

    /**
     * Set number to the document
     */
    public function setNumber(Document $document)
    {
        //set format of document number (XX00000001)
        $document->number = "IQR" . sprintf('%06d', self::currentNum());
    }

    /**
     * Handle the rent "creating" event.
     *
     * @param  AppModelsDocument $document
     * @return void
     */
    public function creating(Document $document)
    {
        $this->setNumber($document);
    }
  }

I’d be happy if you help me to solve this problem. Any additional advice, in this case, would be very appreciated since I’m new in PHP & Laravel.

Advertisement

Answer

“Two requests mean two executions of the script, and two distinct memory spaces. At the end of the first request, the first script ends, and all the changes it made in memory are forgotten. The second script starts from scratch, with all the variables having their default value.” from StackOverflow.

Thanks, Jeto and Elias Soares for explainings.

Here is my solution so far:

public function setNumber(Document $document)
  {
    //Get the highest "id" in the table + 1
    $max_id= Document::max('id') + 1;

    //set format of document number (XX00000001)
    $document->number = 'SQ' . sprintf('%07d', $max_id);
  }
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement