拉拉维尔,最后插入id使用雄辩

时间:2022-10-25 09:39:05

I'm currently using this code to insert data in a table:

我目前正在使用此代码在表中插入数据:

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

And I want to return the last ID inserted but I don't know how to get it.

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

Kind regards!

亲切的问候!

22 个解决方案

#1


268  

After save, $data->id should be the last id inserted.

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

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

#2


75  

xdazz is right in this case, but for the benefit of future visitors who might be using DB::statement or DB::insert, there is another way:

xdazz在本例中是正确的,但是为了将来可能使用DB::语句或DB::insert,有另一种方法:

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

#3


36  

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...

对于任何喜欢Jeffrey Way使用模型的人::在他的laracast 5教程中创建(),他只需将请求直接发送到数据库中,而无需显式地设置控制器中的每个字段,并使用该模型的$fillable进行质量分配(非常重要,对于任何人来说都是如此):我读很多人使用insertGetId()但不幸的是这并不尊重美元fillable白名单,这样你会得到错误与它试图插入_token和任何不是字段在数据库中,设置你想要的东西过滤,等。令我烦恼,因为我想用质量分配和整体编写更少的代码。幸运的是,clever的create方法只是封装了save方法(如上面提到的@xdazz),所以您仍然可以提取最后创建的ID……

public function store() {

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

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

#4


26  

If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:

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

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

Refer : https://laravel.com/docs/5.1/queries#inserts

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

#5


24  

**** For Laravel ****

为Laravel * * * * * * * *

Firstly create an object, Then set attributes value for that object, Then save the object record, and then get the last inserted id. such as

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

$user = new User();        

$user->name = 'John';  

$user->save();

// Now Getting The Last inserted id

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

$insertedId = $user->id;

echo $insertedId ;

#6


12  

In laravel 5: you can do this:

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

#7


9  

Here is how we can get last inserted id in Laravel 4

下面是如何在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.');
    }

#8


8  

here's an example

这里有一个例子

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

#9


7  

Use insertGetId to insert and get inserted id at the same time

使用insertGetId进行插入,同时插入id

From doc

从医生

If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:

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

By Model

通过模型

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

By DB

通过DB

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

For more details : https://laravel.com/docs/5.5/queries#inserts

更多细节:https://laravel.com/docs/5.5/查询#insert

#10


6  

This worked for me in laravel 4.2

这在laravel 4.2中对我很管用

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

#11


3  

after saving model, the initialized instance has the 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

#12


2  

After saving a record in database, you can access id by $data->id

在数据库中保存一条记录后,可以通过$data->id访问id

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

#13


2  

In Laravel 5.2 i would make it as clean as possible:

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

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

#14


2  

For Laravel, If you insert a new record and call $data->save() this function executes an INSERT query and returns the primary key value (i.e. id by default).

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

You can use following code:

您可以使用以下代码:

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

#15


2  

After

$data->save()

$data->id will give you the inserted id,

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

Note: If your autoincrement column name is sno then you should use $data->sno and not $data->id

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

#16


1  

You can do this:

你可以这样做:

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

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

#17


0  

After Saving $data->save(). all data is pushed inside $data. As this is an object and the current row is just saved recently inside $data. so last insertId will be found inside $data->id.So the Resospnse code will be...

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

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

#18


0  

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

#19


0  

Using Eloquent Model

使用的模型

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

Using Query Builder

使用Query Builder

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

#20


0  

For get last inserted id in database You can use

对于在数据库中最后插入的id,您可以使用

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

here $lastInsertedId will gives you last inserted auto increment id.

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

#21


0  

     $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(array('success' => true,'id'=>$recId), 200);

#22


0  

Using Eloquent Model

使用的模型

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;

}

Using Query Builder

使用Query Builder

$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;

For more methods to get Last Inserted Row id in Laravel : http://phpnotebook.com/95-laravel/127-3-methods-to-get-last-inserted-row-id-in-laravel

要获得更多的方法,可以在Laravel中获得最后插入的行id: http://phpnotebook.com/95- laravel/127-3-methods-toget - Last -insert - Row - idin - Laravel。

#1


268  

After save, $data->id should be the last id inserted.

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

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

#2


75  

xdazz is right in this case, but for the benefit of future visitors who might be using DB::statement or DB::insert, there is another way:

xdazz在本例中是正确的,但是为了将来可能使用DB::语句或DB::insert,有另一种方法:

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

#3


36  

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...

对于任何喜欢Jeffrey Way使用模型的人::在他的laracast 5教程中创建(),他只需将请求直接发送到数据库中,而无需显式地设置控制器中的每个字段,并使用该模型的$fillable进行质量分配(非常重要,对于任何人来说都是如此):我读很多人使用insertGetId()但不幸的是这并不尊重美元fillable白名单,这样你会得到错误与它试图插入_token和任何不是字段在数据库中,设置你想要的东西过滤,等。令我烦恼,因为我想用质量分配和整体编写更少的代码。幸运的是,clever的create方法只是封装了save方法(如上面提到的@xdazz),所以您仍然可以提取最后创建的ID……

public function store() {

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

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

#4


26  

If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:

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

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

Refer : https://laravel.com/docs/5.1/queries#inserts

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

#5


24  

**** For Laravel ****

为Laravel * * * * * * * *

Firstly create an object, Then set attributes value for that object, Then save the object record, and then get the last inserted id. such as

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

$user = new User();        

$user->name = 'John';  

$user->save();

// Now Getting The Last inserted id

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

$insertedId = $user->id;

echo $insertedId ;

#6


12  

In laravel 5: you can do this:

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

#7


9  

Here is how we can get last inserted id in Laravel 4

下面是如何在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.');
    }

#8


8  

here's an example

这里有一个例子

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

#9


7  

Use insertGetId to insert and get inserted id at the same time

使用insertGetId进行插入,同时插入id

From doc

从医生

If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:

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

By Model

通过模型

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

By DB

通过DB

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

For more details : https://laravel.com/docs/5.5/queries#inserts

更多细节:https://laravel.com/docs/5.5/查询#insert

#10


6  

This worked for me in laravel 4.2

这在laravel 4.2中对我很管用

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

#11


3  

after saving model, the initialized instance has the 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

#12


2  

After saving a record in database, you can access id by $data->id

在数据库中保存一条记录后,可以通过$data->id访问id

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

#13


2  

In Laravel 5.2 i would make it as clean as possible:

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

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

#14


2  

For Laravel, If you insert a new record and call $data->save() this function executes an INSERT query and returns the primary key value (i.e. id by default).

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

You can use following code:

您可以使用以下代码:

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

#15


2  

After

$data->save()

$data->id will give you the inserted id,

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

Note: If your autoincrement column name is sno then you should use $data->sno and not $data->id

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

#16


1  

You can do this:

你可以这样做:

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

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

#17


0  

After Saving $data->save(). all data is pushed inside $data. As this is an object and the current row is just saved recently inside $data. so last insertId will be found inside $data->id.So the Resospnse code will be...

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

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

#18


0  

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

#19


0  

Using Eloquent Model

使用的模型

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

Using Query Builder

使用Query Builder

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

#20


0  

For get last inserted id in database You can use

对于在数据库中最后插入的id,您可以使用

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

here $lastInsertedId will gives you last inserted auto increment id.

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

#21


0  

     $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(array('success' => true,'id'=>$recId), 200);

#22


0  

Using Eloquent Model

使用的模型

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;

}

Using Query Builder

使用Query Builder

$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;

For more methods to get Last Inserted Row id in Laravel : http://phpnotebook.com/95-laravel/127-3-methods-to-get-last-inserted-row-id-in-laravel

要获得更多的方法,可以在Laravel中获得最后插入的行id: http://phpnotebook.com/95- laravel/127-3-methods-toget - Last -insert - Row - idin - Laravel。