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

<?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,但我不知道如何获取它。

亲切的问候!


保存后,$data->id应该是最后插入的id。

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

可以这样使用。

return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);

更新laravel版本试试这个

return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);

这里有一个例子:

public static function saveTutorial(){

    $data = Input::all();

    $Tut = new Tutorial;
    $Tut->title = $data['title'];
    $Tut->tutorial = $data['tutorial'];   
    $Tut->save();
    $LastInsertId = $Tut->id;

    return Response::json(array('success' => true,'last_id'=>$LastInsertId), 200);
}

xdazz在这种情况下是正确的,但为了将来可能使用DB::statement或DB::insert的访问者的利益,还有另一种方法:

DB::getPdo()->lastInsertId();

下面是我们如何在Laravel 4中获得最后一个插入id

public function store()
{
    $input = Input::all();

    $validation = Validator::make($input, user::$rules);

    if ($validation->passes())
    {

     $user= $this->user->create(array(
            'name'              => Input::get('name'),
            'email'             => Input::get('email'),
            'password'          => Hash::make(Input::get('password')),
        ));
        $lastInsertedId= $user->id; //get last inserted record's user id value
        $userId= array('user_id'=>$lastInsertedId); //put this value equal to datatable column name where it will be saved
        $user->update($userId); //update newly created record by storing the value of last inserted id
            return Redirect::route('users.index');
        }
    return Redirect::route('users.create')->withInput()->withErrors($validation)->with('message', 'There were validation errors.');
    }

在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;
    }
}

这在laravel 4.2中是可行的

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

For anyone who also likes how Jeffrey Way uses Model::create() in his Laracasts 5 tutorials, where he just sends the Request straight into the database without explicitly setting each field in the controller, and using the model's $fillable for mass assignment (very important, for anyone new and using this way): I read a lot of people using insertGetId() but unfortunately this does not respect the $fillable whitelist so you'll get errors with it trying to insert _token and anything that isn't a field in the database, end up setting things you want to filter, etc. That bummed me out, because I want to use mass assignment and overall write less code when possible. Fortunately Eloquent's create method just wraps the save method (what @xdazz cited above), so you can still pull the last created ID...

public function store() {

    $input = Request::all();
    $id = Company::create($input)->id;

    return redirect('company/'.$id);
}

保存模型后,初始化实例的id为:

$report = new Report();
$report->user_id = $request->user_id;
$report->patient_id = $request->patient_id;
$report->diseases_id = $request->modality;
$isReportCreated = $report->save();
return $report->id;  // this will return the saved report id

将记录保存到数据库后,可以通过$data->id访问id

return Response::json(['success' => true, 'last_insert_id' => $data->id], 200)

在Laravel 5.2中,我会让它尽可能的干净:

public function saveContact(Request $request, Contact $contact)
{
   $create = $contact->create($request->all());
   return response()->json($create->id,  201);
}

为劳拉***

首先创建一个对象,然后为该对象设置属性值,然后保存对象记录,然后获取最后插入的id。如

$user = new User();        

$user->name = 'John';  

$user->save();

//现在获取最后插入的id

$insertedId = $user->id;

echo $insertedId ;

如果表有一个自动递增的id,使用insertGetId方法插入一条记录,然后检索id:

$id = DB::table('users')->insertGetId([
    'email' => 'john@example.com',
    'votes' => 0
]);

参考:https://laravel.com/docs/5.1/queries插入


对于Laravel,如果你插入一个新记录并调用$data->save(),这个函数执行一个insert查询并返回主键值(默认为id)。

你可以使用以下代码:

if($data->save()) {
    return Response::json(array('status' => 1, 'primary_id'=>$data->id), 200);
}

$data->save()

$data->id会给你插入的id,

注意:如果您的自增列名是sno,那么您应该使用 $data->sno而不是$data->id


在save $data之后->save()。所有数据都被推入$data内。因为这是一个对象,当前行刚刚保存在$data中。所以last insertId将在$data->id中找到。

响应代码为:

return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);

你可以这样做:

$result=app('db')->insert("INSERT INTO table...");

$lastInsertId=app('db')->getPdo()->lastInsertId();

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

使用insertGetId同时插入和获取插入id

从医生

如果表有一个自动递增的id,则使用insertGetId方法 插入一条记录,然后检索ID:

通过模型

$id = Model::insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]);

通过DB

$id = DB::table('users')->insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]);

详情请访问:https://laravel.com/docs/5.5/queries#inserts


使用雄辩的模型

$user = new Report();        
$user->email= 'johndoe@example.com';  
$user->save();
$lastId = $user->id;

使用查询生成器

$lastId = DB::table('reports')->insertGetId(['email' => 'johndoe@example.com']);

获取数据库中最后插入的id 你可以使用

$data = new YourModelName;
$data->name = 'Some Value';
$data->email = 'abc@mail.com';
$data->save();
$lastInsertedId = $data->id;

这里$lastInsertedId会给你最后插入的自动增量id。


$objPost = new Post;
$objPost->title = 'Title';
$objPost->description = 'Description';   
$objPost->save();
$recId = $objPost->id; // If Id in table column name if other then id then user the other column name

return Response::json(['success' => true,'id' => $recId], 200);

使用雄辩的模型

use App\Company;

public function saveDetailsCompany(Request $request)
{

$createcompany=Company::create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);

// Last Inserted Row ID

echo $createcompany->id;

}

使用查询生成器

$createcompany=DB::table('company')->create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);

echo $createcompany->id;

获取Laravel中最后插入行id的更多方法:http://phpnotebook.com/95-laravel/127-3-methods-to-get-last-inserted-row-id-in-laravel


对于insert ()

例子:

$data1 = array(
         'company_id'    => $company_id,
         'branch_id'        => $branch_id
     );

$insert_id = CreditVoucher::insert($data1);
$id = DB::getPdo()->lastInsertId();
dd($id);

最短的方法可能是在模型上调用refresh():

public function create(array $data): MyModel
{
    $myModel = new MyModel($dataArray);
    $myModel->saveOrFail();
    return $myModel->refresh();
}

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

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

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


可选方法为:

$lastID = DB::table('EXAMPLE-TABLE')
                ->orderBy('id', 'desc')
                ->first();

$lastId = $lastProduct->id;

来自Laravel 5.8版本


你可以用save method获取上次插入的id;

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

所以你可以简单地写:

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

你可以使用$this构造函数变量在当前函数或控制器中实现“使用Laravel Eloquent最后插入Id”(不添加任何额外列)。

public function store(Request $request){
    $request->validate([
        'title' => 'required|max:255',
        'desc' => 'required|max:5000'
    ]);

    $this->project = Project::create([
        'name' => $request->title,
        'description' => $request->desc,
    ]);

    dd($this->project->id);  //This is your current/latest project id
    $request->session()->flash('project_added','Project added successfully.');
    return redirect()->back();

}

你也可以这样尝试:

public function storeAndLastInrestedId() {
    $data = new ModelName();
    $data->title = $request->title;
    $data->save();

    $last_insert_id = $data->id;
    return $last_insert_id;
}

您可以很容易地获取最后插入的记录Id

$user = User::create($userData);
$lastId = $user->value('id');

从DB中最后插入的记录中获取Id是一个很棒的技巧。


这就是它是如何为我工作的,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;
  

有几种方法可以获取最后插入的id。所有这些都是基于您在插入时使用的方法。在这种情况下,你可以得到最后一个。

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

对于其他人谁需要知道如何获得最后插入id,如果他们使用其他插入方法,这里是如何:

使用create()方法 书=书:美元:创建(['名字' = > ' Laravel战士']); $lastId = $book->id; 使用insertGetId () $id = DB::table('books')->insertGetId(['name' => 'Laravel warrior']);$lastId = $id; 使用lastInsertId()方法 $lastId = DB::getPdo()->lastInsertId();

参考https://easycodesolution.com/2020/08/22/last-inserted-id-in-laravel/