Search code examples
mysqllaravelmodelincrementlaravel-6

Laravel Model get next increment ID when the Table linked with Model is Non-AutoIncrement


As I mentioned in Question, the current Laravel 6.0 project I am working on has bit weird DB setup, where the Model's(the MainModel here) MySQL table has been set with AutoIncrement as NULL. And client won't allow to change the Table's definition at all.

I want to reliably find the next and previous IDs of the Model(since I can't find from table as AutoIncrement is set to NULL) before inserting record, so that I can make an entry of relevant record(for eg. image(s) of a testimonial/faq or any WYSIWYG content field) into another referential table first, by correctly inserting the main Model's ID into the refrential ID field of that another table.

Currently I have this in my main Model, but the next method doesn't reliably return the exact incremented ID consistently:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Te7aHoudini\LaravelTrix\Traits\HasTrixRichText;

class [MainModel] extends Model
{
    use HasTrixRichText;

    protected $guarded = [];
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $connection = '[connection1]';
    protected $table = '[main_table]';
    protected $fillable = ['id', '[titlefield]', '[wysiwyg_field]'];

    /**
     *  Setup model event hooks
     */
    public static function boot()
    {
        parent::boot();
        self::creating(function ($model) {
            $model->id = $model->max('id') + 1;
        });
    }

    /**
     * Get next available Faq Id
     */
    public function next()
    {
        return ++$this->id;
    }
}

Any help is appreciated...


Solution

  • As I understand you are confused about how to call statically model queries. You can achieve the same logic by using a static self-reference static.

    public static function next()
    {
        return static::max('id') + 1;
    }
    

    This would be equivalent to.

    MainModel::max('id');
    

    Bonus to make it a transaction to avoid id clashing. This can lock the database in fun ways, but will avoid you have the same ids, something similar to this, very simple example.

    DB::transaction(function () {
        $id= MainModel::next();
    
        $newModel = MainModel::create(['id' => $id]);
    });