laravel insert get id code example

Example 1: laravel query builder get last insert id

$id = DB::table('users')->insertGetId(
    ['email' => '[email protected]', 'votes' => 0]
);

Example 2: laravel get last id

DB::table('myTable')->orderBy('id','desc')->first();

Example 3: laravel get ID from insert

$data = User::create(['name'=>'first']);
dd($data->id);

Example 4: laravel model save get id

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

Example 5: laravel create get id

$id = $this->create($data)->id;

Example 6: laravel create get id

$user = User::create([
    'username' => $data['username'] . ' ' . $data['username2'],
    'mail' => $data['mail'],
    'password' => bcrypt($data['password']),
]);

$userInfo = UserInformation::create([
    'user_id' => $user->id,
    'current_food' => $food,
    'current_level' => $level,
]);

Tags:

Php Example