"Laravel 5.1" add user and project with userId
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')
->first();
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.
Answer
If you are trying to get the ID of a newly created record try:
$user = User::create(['name'=>'Stefano']);
$user->id
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?