"Laravel 5.1" add user and project with userId

- 1 answer


I have a form where an user can post a project to the database together with making a new user where both are linked together.

Usersid and projects.user_id values in the table.But, I have a small problem. If I get the last id from the users table and use that one +1 for the next id it works. but if an user gets deleted before adding the new project with id it can get really messy when the application launches.

let's say I got the last user as id 5 in the table. but, someone deleted it and I made a new project with a new user the day after.Now the next id will be id 6. but according to my code it reflects 5 in the projects_table but in the users_table it becomes 6.

I was wondering if someone can suggest me a function that I could use for having the right id's?

function for getting the last id

    public static function getLastRow(){
            $data =  DB::table('users')->select('id')
                ->orderBy('id', 'desc')
            return $data->id;

before validator i count the last id for adding it to projects

 $lastidplus = (int)User::getLastRow() + 1;

in my validator i have this :

'user_id' => $lastidplus,

NOTE:: this works but if in the future the last row in the users table gets deleted. there will come an chain reaction of false ids in the corresponding projects table as he will always have 1 difference. and I wantto make that impossible.




If you are trying to get the ID of a newly created record try:

$user = User::create(['name'=>'Stefano']);
source: stackoverflow.com