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
How to Check If MySQL Results Returned Empty in PHP
Php to View Pdf on Web Page and Disable User to Download
Download a Facebook Video (.Mp4) Via PHP
Loop Row in Bootstrap Every 3 Columns
Patch and Put Request Does Not Working With Form-Data
How to Use a Findby Method With Comparative Criteria
How to Resolve MySQL Port 3306 Error on Wamp
Get All Hrefs from String But Then Replace Via Another Method
How to Get PHP Errors to Display
Generate an N-Digit Random Number
Update Data on a Page Without Refreshing
How to Fix Undefined Offset: 0 in Laravel Blade
Laravel - Getting Current Month and Year Only