Custom function in model

I neet to generate next number based on month and year. Is this proper way to do it or can it be done differently?

class Foo extends Model

    public function getNextNumber()
        $result = DB::select('SELECT COALESCE(MAX(number), 0) + 1 AS number FROM foo AS t2 WHERE MONTH(generated_at) = MONTH(CURDATE()) AND YEAR(generated_at) = YEAR(CURDATE())');

        return head($result)->number;

When create a new record:

$foo = new Foo();

$foo->template = 'template1';
$foo->number = $foo->getNextNumber();
$foo->generated_at = DB::raw('NOW()');


Source: laravel

Leave a Reply