我目前正在使用下面的代码在一个表中插入数据:

<?php

public function saveDetailsCompany()
{
    $post = Input::All();

    $data = new Company;
    $data->nombre = $post['name'];
    $data->direccion = $post['address'];
    $data->telefono = $post['phone'];
    $data->email = $post['email'];
    $data->giro = $post['type'];
    $data->fecha_registro = date("Y-m-d H:i:s");
    $data->fecha_modificacion = date("Y-m-d H:i:s");

    if ($data->save()) {
        return Response::json(array('success' => true), 200);
    }
}

我想返回插入的最后一个ID,但我不知道如何获取它。

亲切的问候!


当前回答

这在laravel 4.2中是可行的

$id = User::insertGetId([
    'username' => Input::get('username'),
    'password' => Hash::make('password'),
    'active'   => 0
]);

其他回答

虽然这个问题有点过时了。我的快速解决方案是这样的:

$last_entry = Model::latest()->first();

但我猜它很容易受到频繁使用的数据库的竞争条件的影响。

public function store( UserStoreRequest $request ) {
    $input = $request->all();
    $user = User::create($input);
    $userId=$user->id 
}

这在laravel 4.2中是可行的

$id = User::insertGetId([
    'username' => Input::get('username'),
    'password' => Hash::make('password'),
    'active'   => 0
]);

这就是它是如何为我工作的,family_id是自动增量的主键,我使用Laravel7

    public function store(Request $request){
        $family = new Family();
        $family->family_name = $request->get('FamilyName');
        $family->family_no = $request->get('FamilyNo');
        $family->save();
        //family_id is the primary key and auto increment
        return redirect('/family/detail/' .  $family->family_id);
    }

同样在Model Family文件中,应该将增量设置为true,否则上面的$ Family——>family_id将返回空

    public $incrementing = true;
  

在laravel 5中:你可以这样做:

use App\Http\Requests\UserStoreRequest;
class UserController extends Controller {
    private $user;
    public function  __construct( User $user )
    {
        $this->user = $user;
    }
    public function store( UserStoreRequest $request )
    {
       $user= $this->user->create([
            'name'              => $request['name'],
            'email'             => $request['email'],
            'password'          => Hash::make($request['password'])
        ]);
        $lastInsertedId= $user->id;
    }
}