How to Get Next Id of Autogenerated Field in Laravel for Specific Table

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

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]);
});

How to let ID autoincrement start from certain number in Laravel Migration

add a record with id (desired id -1) and then delete it.

If you add a record with id 999, and then delete it, next record will have id 1000. You can also use SQL identity on your database

Add new auto increment column to existing table

Drop the primary key in a separate migration and remove $table->primary('id'). Adding an AUTO_INCREMENT column automatically creates a primary key:

Schema::table('item_tag', function (Blueprint $table) {   
$table->dropPrimary();
});

Schema::table('item_tag', function (Blueprint $table) {
$table->unsignedInteger('id', true)->first();
});

You can also simplify the second migration:

Schema::table('item_tag', function (Blueprint $table) {
$table->increments('id')->first();
});

set id value in AUTO_INCREMENT field with laravel

Add id in your fillable array in Point model class.

protected $fillable = [
'id'
];

Get the Last Inserted Id Using Laravel Eloquent

After save, $data->id should be the last id inserted.

$data->save();
$data->id;

Can be used like this.

return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);

For updated laravel version try this

return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);


Related Topics



Leave a reply



Submit